Fun with lambda and map
Andrew Gaul
gaul at spam.utexas.edu
Tue Feb 12 07:03:25 EST 2002
In article <3c566a21.22129828 at news.t-online.de>, Gerson Kurz wrote:
> primes = lambda o:map(lambda a:filter(None,(map(lambda i:map(lambda x:a.__setitem__(x,0),range(2*i,o,i)),range(2,o)),a)[1])[1:],[range(o)])[0]
>
> fibonacci = lambda x:map(lambda o:(map(lambda c:map(lambda l:o.__setslice__(l[0],l[1],l[2]),([o[2]+3,o[2]+4,[o[0]]],[0,3,[o[1],reduce(lambda x,o:x+o,o[:2]),o[2]+1]])),range(x)),o)[1],[[1,1,0]+range(x)])[0][3:]
>
> (Note: These probably need python 2.2 to work because of the lambda
> scope thing)
Here's a shorter implementation that works with both 1.5 and 2.2 that
involves some cleverness:
fibonacci = lambda z: map(lambda n, f=(lambda f,x,a,b: \
[x<=0 and b, x>0 and f(f,x-1,b,a+b)][x>0]): f(f,n,0,1), range(z))
It's not as nice as the Haskell version:
fibonacci n = take n fib
where fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
Enjoy!
--
Andrew Gaul
http://gaul.org/
More information about the Python-list
mailing list