2004 example, passing function error

alex23 wuwei23 at gmail.com
Tue May 13 22:54:14 EDT 2008


On May 14, 11:40 am, globalrev <skanem... at yahoo.se> wrote:
> so just a mistake on his part? but it looks like he just copied his
> shell...has there been a change since 2004 inr egards to how you can
> pass functions as arguments to functions??

Adding the value argument (x) to the compose function really limits
its usefulness as well. Given the author was talking about functions
as first class objects, it makes more sense for compose to return a
function, rather than to perform several function calls and return a
value.

Here, compose creates a new function that performs first 'f' then 'g'
on a value:

>>> def compose(f, g):
...     def _compose(x):
...         return f(g(x))
...     return _compose
...
>>> compose(sqr, cube)
<function _compose at 0x00B7BEB0>
>>> compose(sqr, cube)(2)
64

The advantage being you can easily create function chains this way:

>>> sqrcube = compose(sqr, cube)
>>> sqrcube(2)
64

And because they're functions, you can use them with compose to
construct more complex functions:

>>> cubesqrcube = compose(cube, sqrcube)
>>> cubesqrcube(2)
262144

Just to show they're functionally the same:

>>> cubesqrcube(2) == cube(sqrcube(2)) == cube(sqr(cube(2)))
True

I like this approach because it separates the function composition
from its execution. But you can also achieve much the same by using
functools.partial (in 2.5+):

>>> def compose(f, g, x): return f(g(x))
...
>>> compose(sqr, cube, 2)
64
>>> from functools import partial
>>> sqrcube = partial(compose, sqr, cube)
>>> sqrcube(2)
64
>>> cubesqrcube = partial(compose, cube, sqrcube)
>>> cubesqrcube(2)
262144

Hope this helps.

- alex23



More information about the Python-list mailing list