Is there a function that applies list of functions to a value?
fp2161 at gmail.com
fp2161 at gmail.com
Thu Aug 29 17:48:12 EDT 2013
On Thursday, August 29, 2013 11:05:38 PM UTC+2, Chris Angelico wrote:
> On Fri, Aug 30, 2013 at 6:50 AM, <fp2161 at gmail.com> wrote:
>
> > My way is so obvious that it may not be that interesting...
>
> >
>
> > def func4(f1,f2,f3,f4):
>
> > def anon(x):
>
> > f1(f2(f3(f4(x))))
>
> > return anon
>
>
>
> Or have it return the result of f1. And then, since it's an anonymous
>
> function that simply returns an expression, I'd write it as:
>
>
>
> def func4(f1,f2,f3,f4):
>
> return lambda x: f1(f2(f3(f4(x))))
>
>
>
> Of course, that's still restricted to precisely four args. Extending
>
> this concept to a variable number of arguments is, uhh, left as an
>
> exercise to the reader. Which will probably end up going back to
>
> reduce(). :)
>
>
>
> ChrisA
Here is the generalisable version:
def comp(*func):
def anon(x):
res=x
for f in func:
res=f(res)
return res
return anon
you can then compose your function in __main__:
f4=comp(f5,f6,f7)
and call it:
print(x) ...
(I hope that Chris is happy now...)
More information about the Python-list
mailing list