how to write function that returns function

Bjorn Pettersen BPettersen at NAREX.com
Tue May 14 19:18:17 EDT 2002


> From: Paul Graham [mailto:spam at bugbear.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.

It's bad form to ask for help on your homework problems, after all *YOU*
are the one who is supposed to learn something...

> Here, in Scheme, is what I want to write:
> 
> (define foo (x) (lambda (y) (+ x y)))

Well (+ x y) is spelled 'x + y' in Python.
(lambda (y) ...) is spelled 'lambda y: ...'
and (define foo (x) ...) is spelled

  def foo(x):
      ...

putting it all together you get:

  def foo(x):
      lambda y: x + y

very straight-forward. Now for some arcane matters.

If you're running Python 2.2+ you're done.
If you're running Python 2.1, you need to put 'from __future__ import
nested_scopes' at the top of your module.
If you're running Python 1.5.x, you need to change the lambda to:

  lambda y, x=x: x + y

the x=x creates a binding local to the lambda which was required for the
1.5.x versions.

[snip]

> [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.]

If Guido can deal with the spam he gets from posting here, so can you.

-- bjorn





More information about the Python-list mailing list