3

I have a simple source.

def h(x):
    return x + 1

def m(x):
    return x + 2

def n(x):
    return x * 10

def function_aggregator(fun_list, num):
    return_fun = None
    for fun in fun_list[::-1]:
        if return_fun:
            return_fun = fun(return_fun)
        else:
            return_fun = fun(num)
    return return_fun

if __name__ == "__main__":
    lst = [h, m, n]
    y = function_aggregator(lst, 4)
    print(y)

Is there any way to make the function_aggregator method receive just the list and return a callable the will be the same as h(m(n(<any_number>))

Ilia S.
  • 780
  • 7
  • 19

2 Answers2

1

The previous answer is pretty close. The exact answer is:

def function_aggregator(fun_list):
    def wrapper(arg):
        for fun in reversed(fun_list):
            arg = fun(arg)
        return arg
    return wrapper


if __name__ == "__main__":
    lst = [g, f, n, m, h]
    p = function_aggregator(lst)
    x = 3
    print("p(x): {}".format(p(x)))

Thanks to Zero Piraeus commet

Ilia S.
  • 780
  • 7
  • 19
0

It could be done using closure:

def function_aggregator(*func_list):
    def aggregate(num):
        for func in reversed(func_list):
            num = func(num)
        return num
    return aggregate

if __name__ == "__main__":
    myfunc = function_aggregator(h, m, n)
    print(myfunc(4))

Notes

  • function_aggregator now takes an arbitrary number of functions
  • Inside, it defines another function, aggregate, this is the callable you are talking about.
  • function_aggregator returns that callable, AKA aggregate to the caller
  • The caller then give it a name, myfunc in this case
  • From then on, we can treat myfunc as a function which takes 1 argument and return something
Hai Vu
  • 37,849
  • 11
  • 66
  • 93