how to write function that returns function

Paul Graham spam at bugbear.com
Tue May 14 19:03:25 EDT 2002


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

but I don't think this is exactly the same thing,
because it returns a function that takes a second
optional argument.  That is a substantial difference.
If the Scheme function is inadvertently called 
(e.g. in someone else's code) with two arguments, it 
would signal an error, whereas the code above would 
quietly give the wrong answer.

I would appreciate it if someone could tell me the
standard way to write this so that it returns a
function of exactly one argument.

Thanks!

[To reply to me directly please use pg at bug<remove>bear.com, 
removing the <remove>, because I don't check spam at bugbear.com.]



More information about the Python-list mailing list