Pythonic function composition

Oliver Fromme olli at haluter.fromme.com
Mon Oct 25 17:26:02 CEST 2004


Alan G Isaac <aisaac at american.edu> 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?

There are probably several ways to do it.
The following is the one which come to my mind first.

The trick is to first define a function that composes
two functions, and then use reduce() to apply it to an
arbitrary number of functions.

>>> def compose2 (f, g):
...   def h (x):
...     return f(g(x))
...   return h
...
>>> def compose (fns):
...   return reduce(compose2, fns)
...

Some testing:

>>> def add42 (x): return x + 42
...
>>> def mul2 (x): return x * 2
...
>>> def sub5 (x): return x - 5
...
>>> def div3 (x): return x / 3
...
>>> a = compose((add42, mul2, sub5, div3))
>>> a(1)
27

There's no need to juggle with lambda in this case.
Lambda has its uses, but this isn't one of them.

Best regards
   Oliver

-- 
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)



More information about the Python-list mailing list