lambda functions ?

Paul Rubin http
Mon Feb 5 17:22:05 EST 2007


"Maxim Veksler" <hq4ever at gmail.com> writes:
> >>> def make_incrementor(n):
> ... return lambda x: x + n

Is the same as:

  def make_incrementor(n):
     def inner(x):
        return x + n
     return inner

When you enter make_incrementor, it allocates a memory slot (normally
we'd think of this as a stack slot since it's a function argument, but
it's really in the heap) and copies its argument there.  Then you
create the function "inner" which refers to that memory slot because
of the reference to "n".  Then make_incrementor returns, but since the
returned object still contains the reference to that memory slot, the
memory slot is not freed (this is the part where it becomes important
that the slot is really not on the stack).  So when you call the
returned function, it still can get at that slot.

This style is very common in Scheme programming so you might read a
Scheme book if you want to understand it.  The classic:

  http://mitpress.mit.edu/sicp/

> Could some please try (if even possible) to implement the above code
> without using "lambda" I believe it would help me grasp this a bit
> faster then.

Does the above help?



More information about the Python-list mailing list