writing recursive lambda functions

Francis Avila francisgavila at yahoo.com
Wed Dec 24 13:08:41 CET 2003

Thorsten Rühl wrote in message ...
>Hi there,
>at first i have to say i am very new in python so i have a few problems to
>get along with some things.
>My first problem i can´t handle is to write a recursive lambda function:
>the formal definition is
>letrec map(f) = lambda l. if != NIL then NIL
>       else cons(f(car(l)), map(f)(cdr(l)))
>after i realised that i can´t use if clauses in lambda definition i tried
>to convert the if line in an correspondending boolean operator line:
>def mapp(f):
>    lambda l: l and cons(f(car(l)),(mapp(f)(cdr(l))))
>but it doesn´t work.

You need to return the lambda.  You've been coding too much lisp. ;)

>if i try to use the result in the following way i get an error: object not
>callable but i don´t understand why it is not callable.

Because mapp always returns None (the implicit return value), and None isn't
a callable.

>So i hope this is question is not to nooby and i did´nt waste your time.
>But i really need a little help with this.

I'm not sure why you want to code Python as if it were lisp.  This will only
lead to tears.  It's also quite a bit slower, because calling is expensive
in Python.  (I understand if this is simply an academic exercize, but still,
try to read beyond the formal definitions).

Typical thing you'd do in Python is one line:
[x*x for x in L]

This makes crystal clear what you want to do.  I had to puzzle over that
pseudolisp to figure out the big picture.

Replace x*x with whatever you want.  The recursive '(cons ((car L) (func
(cdr L))))' pattern in lisp is 'for item in sequence' in Python, and there's
no need to pass a lambda into a function factory.

Also, we already have a map (as you noticed, because of your namespace
clash).  So

map(lambda x: x*x, [1,2,3,4])

works.  If you want to curry it, you can do so:

def curry(f, *args):
    def inner(*args2):
        return f(*(args + args2))
    return inner

mapQuad = curry(map, lambda x: x*x)
Francis Avila

More information about the Python-list mailing list