Fun with lambda and map

Gerson Kurz gerson.kurz at t-online.de
Mon Feb 4 10:58:16 EST 2002


On 4 Feb 2002 16:38:07 GMT, ivo at nospamAmaze.nl wrote:

>I extended the calculus a bit with mul (based on your sig :) and pred, 
>hoping that I could fac in lambda, but I guess I've reached pythons lambda 
>limits.
>
>The statement:
>
>fac = lambda q: if_then_else(is_zero(pred(q)))(n1)(mul(q, fac(pred(q))))
>
>will recurse endlessly, because the else-part will always be evaluated
>(but just not used as a result).
>

Well, you can:

IF_ELSE = lambda x:(map(lambda a:a and 1,[x[0]()])[0] and x[1]()) or
x[2](x[3])
fac = lambda n:IF_ELSE([lambda:not n,lambda:n==n,lambda
n:fac(n-1)*n,n])


for i in range(20):
    print i, "->", fac(i)

If you're in a masochistic mood, you can write this in one line:

fac = lambda n:map(lambda x:(map(lambda a:a and 1,[x[0]()])[0] and
x[1]()) or x[2](x[3]),[[lambda:not n,lambda:n==n,lambda
n:fac(n-1)*n,n]])[0]





More information about the Python-list mailing list