compose
H.V
sulfugor at rocketmail.com
Mon May 5 06:43:31 EDT 2003
"xam" <ma at Bell.com> wrote in message news:<4amta.2718$2p.368 at twister.nyc.rr.com>...
> 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?
-----------------
i think your problem is that you're passing a tuple of functions to
your compose while it's supposed to be called with an unpacked tuple.
You need compose(*funcs[1:])(x) in line 2
my compose :)
compose = lambda flist=[]: reduce(lambda f1,f2:lambda x:f2(f1(x)),
flist ,
lambda y:y)
this one handles compose()(x) too .
not too useful but, hey :)
An earlier, more verbose attempt :
def compose(flist=[lambda x:x]):
if flist==[]:
return lambda x:x
elif len(flist)==1 :
return flist[0]
elif len(flist)==2 :
return lambda x: flist[1]( flist[0](x))
#for more than 2 funcs compose first 2 functions and recurse
else :
first = [lambda x: flist[1]( flist[0](x))]
rest = flist[2:]
return compose(first+rest)
sulf
More information about the Python-list
mailing list