Pythonic function composition

Peter Otten __peter__ at web.de
Mon Oct 25 11:23:09 EDT 2004


Alan G Isaac wrote:

> Given a list of functions, it seems there must be a
> Pythonic approach to composition.  Something like
> 
> def compose(fns): return lambda x: reduce(lambda f,g: f(g),fns)(x)
> 
> This will not work because the argument 'x' is not "inside".
> What is the proper formulation?

You need to pass a function that makes a function (a "factory") to reduce():

>>> fns = [lambda x: x+2, lambda x: x*2, lambda x: x*x]
>>> def compose(f, g):
...     def fog(x):
...             return f(g(x))
...     return fog
...
>>> g1 = reduce(compose, fns)
>>> g1(2)
10

The same with lambdas:

>>> g2 = reduce(lambda f, g: lambda x: f(g(x)), fns)
>>> g2(2)
10

Peter




More information about the Python-list mailing list