Home > Software design >  List of functions->single function (in python)
List of functions->single function (in python)

Time:09-21

Say that I have a list of functions: [f1, f2, f3] (in python)

How do I return a single function F:=f3(f2(f1())) (notice that F is of function type). I know that it's possible to do it with .reduce() but I was wondering if there's another way to do it without using libraries.

edit:

Also, notice that the length of the list can be greater than 3

I tried:

def func(list):
  i = 1
  new_function = filters[0]
  while i<=len(filters)-1:
      new_function = filters[i](new_function)
      i =1
  return new_function

but it doesn't work

CodePudding user response:

The problem in your code is that you pass a function as argument with filters[i](new_function).

I would suggest this recursive solution:

def chain(first, *rest):
    return lambda x: first(chain(*rest)(x) if rest else x) 

Example use:

def inc(x):
    return x   1

def double(x):
    return x * 2

def square(x):
    return x * x

f = chain(square, double, inc)

print(f(5))  # ((5 1)*2) ** 2 == 144

CodePudding user response:

I see that in the code you tried, you never actually call the first of your functions. (I also assume that your code starts: def func(filters):

Taking into account that f1() takes no parameter, but the rest take the parameter of the return of the previous function, this should work:

def fit(funcs):
    v = funcs[0]()
    for f in funcs[1:]:
        v = f(v)
    return v

def f1():
    return 42

def f2(x):
    return x

def f3(x):
    return x

fs = [f1, f2, f3]

a = lambda:fit(fs)

print(a())

Output: 42

CodePudding user response:

def get_single_func(func_list):
    def single_func(*args, **kwargs):
        ret = func_list[0](*args, **kwargs)
        for func in func_list[1:]:
            ret = func(ret)
        return ret
    return single_func

        
  • Related