Not entirely serious: recursive lambda?

Paul McGuire ptmcg at austin.rr.com
Sun Jul 20 07:11:55 CEST 2008


On Jul 19, 11:49 pm, Miles <semantic... at gmail.com> wrote:
> On Sat, Jul 19, 2008 at 10:43 PM, Michael Tobis <mto... 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

Here is Michael Tobis's original program, using the functional
approach:

print (lambda f:f(("",reduce(lambda
c,m:c*95+''.join(map(chr,range(32,127))).index(m),
 "!b)'1Mgh0z+fYQ]g::i^<&y~g)cnE-d=K&{GMNQ1gx
+ooY<~L##N'X]P2<@XYXwX3z",
0),f)))(lambda (r,N,f):N and f((" acdefijlmnopqrstuv"[N%19]+r,N/
19,f))or(r,N,f))[0]

Très assombri! (according to Babelfish...).

-- Paul



More information about the Python-list mailing list