[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Shorter lambda expressions
From: |
Mark H Weaver |
Subject: |
Shorter lambda expressions |
Date: |
Wed, 22 Jan 2014 23:51:18 -0500 |
Hello all,
For a short time I liked 'cut' from SRFI-26, but I soon became
frustrated by its limitations, most notably not being able to reference
the arguments out of order or within nested expressions. I don't like
the inconsistent style that results when I use 'cut' wherever possible
and 'lambda' everywhere else. So I just stopped using it altogether.
I prefer what Shiro Kawai did in Gauche: ^ is short for lambda, (^x ...)
is short for (lambda (x) ...), and similarly for all the letters. ^_ is
short for lambda with one ignored argument.
http://blog.practical-scheme.net/gauche/20100428-shorter-names
Here's a module that implements that idea, but takes it slightly
further. It exports the unary lambda shorthands described above, and
also a few non-unary ones: ^xy, ^xyz, ^ab, ^abc, ^uv. It also exports
variants that use λ instead of ^, for a nicer look if you're willing to
venture outside of ASCII.
Finally, it exports the transformer procedure that's bound to all of the
keywords above. It's called 'short-lambda'. Bind it to any keyword
like this:
(define-syntax ^kw short-lambda)
and now (^kw ...) will expand to (lambda (k w) ...).
'short-lambda' splits the keyword into individual characters. The first
character (usually ^ or λ) is ignored. The other characters become the
variable names. Underscores are treated specially: they become gensyms.
Thoughts?
Mark
(define-module (ice-9 short-lambdas)
#:export (^ ^_ λ_
^a ^b ^c ^d ^e ^f ^g ^h ^i ^j ^k ^l ^m
^n ^o ^p ^q ^r ^s ^t ^u ^v ^w ^x ^y ^z
^xy ^xyz ^ab ^abc ^uv
λa λb λc λd λe λf λg λh λi λj λk λl λm
λn λo λp λq λr λs λt λu λv λw λx λy λz
λxy λxyz λab λabc λuv
short-lambda))
(eval-when (expand)
(define short-lambda
(lambda (form)
(syntax-case form ()
((k-id body0 body ...)
(let* ((k-symbol (syntax->datum #'k-id))
(k-name (symbol->string k-symbol))
(chars (cdr (string->list k-name)))
(names (map string chars))
(symbols (map string->symbol names)))
(define (sym->id sym)
(case sym
((_) (car (generate-temporaries '(_))))
(else (datum->syntax #'k-id sym))))
(with-syntax ((ids (map sym->id symbols)))
#'(lambda ids body0 body ...))))))))
(define-syntax-rule (define-short-lambdas k ...)
(begin (define-syntax k short-lambda) ...))
(define-short-lambdas
^ ^_ λ_
^a ^b ^c ^d ^e ^f ^g ^h ^i ^j ^k ^l ^m
^n ^o ^p ^q ^r ^s ^t ^u ^v ^w ^x ^y ^z
^xy ^xyz ^ab ^abc ^uv
λa λb λc λd λe λf λg λh λi λj λk λl λm
λn λo λp λq λr λs λt λu λv λw λx λy λz
λxy λxyz λab λabc λuv)
- Shorter lambda expressions,
Mark H Weaver <=