Function composition
piet at cs.uu.nl
piet at cs.uu.nl
Thu Aug 3 04:15:21 EDT 2000
>>>>> cg at gaia.cdg.acriter.nl (Cees de Groot) (CdG) writes:
CdG> I was showing a Math PhD/Functional programming guy Python, and of
CdG> course he was interested in map, filter, etcetera. He talked about
CdG> function composition, and I did a quick:
CdG> def compose(f, g): return lambda x: f(g(x))
This won't work because python doesn't have nested scopes.
The following works, however:
def compose(f, g):
return lambda x,f=f,g=g: f(g(x))
>>> def compose(f, g):
... return lambda x,f=f,g=g: f(g(x))
...
>>> from math import sin,cos
>>> sincos = compose (sin,cos)
>>> sincos(0)
0.841470984808
>>> sin(1)
0.841470984808
-
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl
More information about the Python-list
mailing list