[Tutor] Globals?

Alan Gauld alan.gauld at freenet.co.uk
Sun Nov 14 00:44:35 CET 2004


PMFJI,

> Here is a CL equiv of what I *think* should happen, unelss someone
has a
> godo reason for it not to belike this:
>
> (defun foo (n) (lambda (i) (incf n i)))

But this is not really equivalrent to what you posted in Python since
you pass the increment value to the lambda. If we allow the lambda
to take parameters we must surely allow the default value trick too?

So the nearest equivalent in Python, which seems to do what I
think the CL does... is this:

>>> def f(n):
...   def g(i, x=n):
...     x = x + i
...     return x
...   return g
...
>>> b = f(2)
>>> b(3)
5
>>> b(9)
11
>>> c = f(7)
>>> c(4)
11
>>> c(22)
29
>>>

So by passing the outer parameter into the scope of the returned
function as a default value we get very near to true closure
behaviour.

What are you still missing?

Alan G.



More information about the Tutor mailing list