Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

how to write function that returns function

0 views
Skip to first unread message

Bjorn Pettersen

unread,
May 14, 2002, 7:18:17 PM5/14/02
to
> From: Paul Graham [mailto:sp...@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@bug<remove>bear.com,
> removing the <remove>, because I don't check sp...@bugbear.com.]

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

-- bjorn


Fernando Rodríguez

unread,
May 15, 2002, 2:57:51 PM5/15/02
to
On Tue, 14 May 2002 17:18:17 -0600, "Bjorn Pettersen" <BPett...@NAREX.com>
wrote:

>> From: Paul Graham [mailto:sp...@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...

True, but personally I consider far more irritating this pedantic attitude
that assumes that _all_ questions must be homework assignments. This is
unfortunately common in comp.lang.scheme and comp.lang.lisp. Let's keep it
away from comp.lang.python.

FYI: http://www.bugbear.com/bio.html

-----------------------
Fernando Rodriguez

0 new messages