Python λ Shorthand
In Python a lambda expression (anonymous function) is created with the lambda keyword:
map(lambda x: x+1, [1,2,3])
Some Scheme interpreters such as Dr. Scheme allow the λ symbol (U+03BB) as a shorthand for lambda. I started wondering what this would look like in Python. For example:
map(λ x: x+1, [1,2,3])
Or for a slightly more gratuitously complex example, a recursive factorial with the Y combinator:
Y = (λ X:
(λ p:
X(λ arg: p(p)(arg)))
((λ p:
X(λ arg: p(p)(arg)))))
F = (λ f: (λ x: (x*f(x-1) if x > 0 else 1)))
fact = Y(F)
fact(5) => 120
The interpreter changes to make this work this are quite simple. All it requires is small change to the grammar, an update to the syntax checker, and a hack in the parser generator to treat characters with the high-bit set as though they were in the alpha class.
There are a few cases where the shorthand is beneficial. For example, compare:
[i for i in lst if i > 42]
to:
filter(λ x: x > 42, lst)
While list comprehensions are the standard python way to accomplish this, I do like how the predicate comes first in the latter version.
Also, pretty much all of the functions in the itertools module could work nicely with the shorthand form:
itertools.groupby(lst, λ x: x.somevalue)
Even so this is probably isn’t something that would be worth adding to the language. Lambda expressions are rarely useful in Python so a shorthand form is not going at add much benefit compared to the added language complexity. Not to mention the need for a UTF-8 aware editor and terminal.
Using It
Since λ probably doesn’t appear on your keyboard a certain amount of editor configuration is required. The easiest way in emacs is to define a key binding that inserts the character:
(global-set-key "\C-c\C-l" (lambda () (interactive) (insert "λ")) )
Alternatively, abbrev-mode can insert this character whenever the word lambda is typed:
(define-abbrev-table 'global-abbrev-table
'(("lambda" "λ" nil 0)))
To build an interpreter with this enabled you’ll need this patch applied to a recentish checkout of python 3k. I don’t know if it would work on earlier versions.
Update: On reddit, gwern pointed out that it’s better to translate from lambda -> λ in the editor display rather than embed this symbol in the text. There is (of course) elisp to do this.