how to write function that returns function

Justin Shaw wyojustin at hotmail.com
Wed May 15 21:25:35 EDT 2002


With nested_scopes you can avoid the default argument:

from __future__ import nested_scopes
def addn(x)
    return lambda y: x + y

will do what you want.

Justin Shaw

"Paul Graham" <spam at bugbear.com> wrote in message
news:4f52f844.0205141503.40000c50 at posting.google.com...
> 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