how to write function that returns function
Fernando RodrÃguez
frr at easyjob.net
Wed May 15 03:21:46 EDT 2002
On 14 May 2002 16:03:25 -0700, spam at bugbear.com (Paul Graham) wrote:
>I am not a Python expert, and I'm hoping someone
>can tell me how in Python to write a function
>of one argument x that returns a function of one
>argument y that returns x+y.
>
>Here, in Scheme, is what I want to write:
>
>(define foo (x) (lambda (y) (+ x y)))
>
>I found on the web a page that says I could define
>this as follows:
>
>def addn(x):
> return lambda y,z=y: x+z
Get a recent version of Python that includes 'nested scopes' a la Lisp, and
try:
>>> from __future__ import nested_scopes # Turn on nested scopes
>>> def f(x):
def g(y):
return y +x
return g
>>> adder = f(3)
>>> adder(4)
7
BTW, this is not exactly the same behavior you find in Lisp. For example:
x = 0 #Global variable
def f():
x = 3 # Doesnt create a dynamic binding, it creates a new local variable
return x
The 'x = 3' doesn't "setf", it "let"s
I find this behavior disturbing, and I hope special variables in Arc will
behave as in Common Lisp.
Good luck with Arc! :-)
-----------------------
Fernando Rodriguez
More information about the Python-list
mailing list