[racket] hack: implicit function arguments
This is very similar to supercut:
http://github.com/jeapostrophe/exp/blob/master/scut.ss
scut allows you to put any expression inside it and it will turn it
into a function. The arguments come from use of _. If you have _i then
it will be the ith argument. If you have _string then the function
will take a "string" keyword argument. The function takes as many
arguments as the maximum i you use inside it. Finally, _... gives you
the rest arg. The bottom of that file has many examples, here are a
few:
((scut _0) 1) => 1
((scut (+ _0 (/ _1 _2)))
1 2 3)
=> (+ 1 (/ 2 3))
((scut (+ _lhs _lhs _rhs)) #:lhs 1 #:rhs 2)
=> 4
((scut (apply + _0 _...))
1 2 3)
=> 6
On Fri, Aug 13, 2010 at 11:01 PM, Jon Rafkind <rafkind at cs.utah.edu> wrote:
> I came up with this little hack that lets you avoid giving an explicit
> argument list to functions. Arguments are discovered by usages of
> underscores followed by a number, like _1 and _2. Partly inspired by scala;
> sure to make your blood boil if you love hygiene.
>
> ;;; usage
> (define/implicit foo1 (printf "~a ~a ~a\n" _8 _9 _8))
> (foo1 5 12)
>
> ;;; code
> #lang racket/base
>
> (require (for-syntax racket/base
> racket/list
> syntax/parse
> )
> racket/stxparam)
>
> (define-syntax-rule (implicits all thing ...)
> (begin
> (define-syntax-parameter thing (lambda (stx)
> (raise-syntax-error #f (format "~a can only
> be used in a
> define/implicit function" 'thing))))
> ...
> (provide thing ...)
> (define-for-syntax all (list #'thing ...))))
>
> (implicits all-implicits _1 _2 _3 _4 _5 _6 _7 _8 _9 _10)
>
> (provide define/implicit lambda/implicit)
> (define-syntax (lambda/implicit stx)
> (define (find-implicits stx)
> (define-syntax-class implicit
> [pattern x:identifier
> #:when (ormap (lambda (y)
> (free-identifier=? y #'x))
> all-implicits)])
> (remove-duplicates
> (filter values
> (syntax-parse stx
> [x:implicit (list #'x)]
> [(x ...) (apply append (map find-implicits (syntax->list #'(x
> ...))))]
> [else (list #f)]))
> free-identifier=?))
> (syntax-parse stx
> [(_ body ...)
> (define implicit-arguments (find-implicits stx))
> (with-syntax ([(new-arg ...) (generate-temporaries implicit-arguments)]
> [(implicit ...) implicit-arguments])
> #'(lambda (new-arg ...)
> (syntax-parameterize ([implicit (make-rename-transformer
> #'new-arg)] ...)
> body ...)))]))
>
> (define-syntax-rule (define/implicit name body ...)
> (define name (lambda/implicit body ...)))
>
> _________________________________________________
> For list-related administrative tasks:
> http://lists.racket-lang.org/listinfo/users
>
--
Jay McCarthy <jay at cs.byu.edu>
Assistant Professor / Brigham Young University
http://teammccarthy.org/jay
"The glory of God is Intelligence" - D&C 93