Not entirely serious: recursive lambda?

Miles semanticist at gmail.com
Sun Jul 20 00:49:55 EDT 2008


On Sat, Jul 19, 2008 at 10:43 PM, Michael Tobis <mtobis at gmail.com> wrote:
> Can a lambda call itself without giving itself a name?

Kind of.  There's a couple ways I know of.

The functional way, which involves the lambda receiving itself as an argument:

(lambda f: f(10, f))(lambda n, f: n and (sys.stdout.write("%d\n" % n)
or f(n-1,f)))

The stack frame examination way:

import sys, inspect, new
(lambda:sys.stdout.write('recurse\n') or
new.function(inspect.currentframe().f_code, globals())())()

The functional way is probably harder to grok unless you've studied
lambda calculus or had experience with "real" functional languages (I
haven't).  For fun, try throwing a Y combinator in there.

-Miles



More information about the Python-list mailing list