compose
Eric Brunel
eric.brunel at pragmadev.com
Mon May 5 05:48:06 EDT 2003
xam wrote:
> i've been truing to get this 'simple' code to work,
> def compose(*funcs):
> ... if len(funcs)>1:
> ... return lambda x:funcs[0](compose(funcs[1:])(x))
> ... else: return lambda x:funcs[0](x)
>
>>>>compose(add_5, mul_3, sub_2)(2)
>>>
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> File "<interactive input>", line 3, in <lambda>
> File "<interactive input>", line 4, in <lambda>
> TypeError: 'tuple' object is not callable
> does anyone want to give it a shot?
Let me guess: have you done any Lisp before? ;-)
Try it like this:
def compose(*funcs):
if len(funcs)>1:
return lambda x:funcs[0](compose(*funcs[1:])(x))
else:
return lambda x:funcs[0](x)
If you don't put the '*' in front of the funcs[1:] in the first recursive call,
you call compose with a single argument which is a tuple. Another way would be
to write:
def compose(*funcs):
if len(funcs)>1:
return lambda x:funcs[0](apply(compose, funcs[1:])(x))
else:
return lambda x:funcs[0](x)
Try to print funcs at the beginning of compose with both versions to see what I
mean.
HTH
--
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list
mailing list