Lambda Forms Question

Alex Martelli aleaxit at yahoo.com
Thu Oct 19 06:07:37 EDT 2000


"Scott Weisel" <sweisel at drew.edu> wrote in message
news:39EE3CC1.E2B07AB7 at drew.edu...
> I'm working with Python on a school project and while I was reading the
> documentation I was quite surprised to find out that Python has some
> features of Lisp.

Why surprised?  "Every language wants to be Lisp"...:-).

> Since we're using Scheme, a variant of Lisp in class, I
> was hoping to use the Lisp feature in Python, but I'm having trouble
> implementing it.
>
> The example that the online documentation gives is
> def make_incrementor(n):
>          return lambda x, incr=n: x+incr
> which returns a function.  Is there any way to write the program so a
value
> is returned, rather than a function.

A function IS a value.  That's the whole point of higher-order functions
such as this one -- returning a constructed function as their result.

Perhaps you can clarify how you would want to call the result-function...?


> Also, how do I write the functions by themselves.  I wrote
> lambda x: x*x
> but I have no way to call it.

You can call it contextually:

>>> (lambda x: x*x)(4)
16

or you can give it a name, and "call the name":

>>> square = lambda x: x*x
>>> square(5)
25

which is (of course) quite nearly equivalent to:

>>> def square1(x):
 return x*x

>>> square1(6)
36

but not quite...:

>>> square.func_name
'<lambda>'
>>> square1.func_name
'square1'

the function-object built via lambda does not know
its name, while the one built via def does.


You can also put the reference to the function object
(built in either way) in any other 'slot' you please:

>>> mylist=[]
>>> mylist.append(lambda x: x*x)
>>> mylist[0](7)
49
>>> mydict={}
>>> mydict['foo']=lambda x: x*x
>>> mydict.get('foo')(8)
64

etc, etc.  Really, a function-object is a first class
citizen, you can build one (with limitations) with the
lambda syntax (or with def, or with new.function...),
you can refer to it in any way you please, and you
can call it (directly, via apply, via map, etc) by
fetching back that reference in whatever appropriate way.


Alex






More information about the Python-list mailing list