# Fun with lambda and map

Andrew Gaul gaul at spam.utexas.edu
Tue Feb 12 07:55:23 EST 2002

```In article <slrna6i14c.sp.gaul at bifrost.cs.utexas.edu>, Andrew Gaul wrote:
> 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) ]

My apologies for following-up to my own post, but I've written something
more horrible:

fibonacci = lambda z, f=(lambda f,x,l: \
[x<=0 and l, x>0 and f(f,x-1,l+[l[-1]+l[-2]])][x>0]): f(f,z-2,[1,1])

Here's an explanation so that this post isn't totally frivolous:
Since we are trying to write the fibonacci in one line, it would seem
that recusion is impossible because any inner function will be a lambda
expression and thus nameless.  We can give this inner function a name
using a default parameter, but the inner lambda won't know about it
because the function name isn't bound yet.  If we pass the function name
as one of the parameters, we can use this to recurse.  There is a bit of
junk to emulate C's short-circuting ?: expression, which is documented
in the Python Cookbook
(http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52310).

--
Andrew Gaul
http://gaul.org/

```