Search code examples
pythonfunctools

Python/Cython return Chained function


I am trying to return a chained function

In the below I would like to give it a list of values that map to functions. For example from the code below

get_function([0,1,2])

returns the function

fun(x , [a,b,c]) = a*b/x**c = mult(div(pow(x,c),b),a)

What I have so far is close

def get_function(function_params):
    def fun(x,params):
        func = x
        for i in range(1,len(function_params)):
            if function_params[i] == 0:
                func = pow(func,params[-i])
            elif function_params[i] == 1:
                func = div(func,params[-i])
            elif function_params[i] == 2:
                func = mult(func,params[-i])
        return func
    return fun

Obviously I could use this giant list of if statements but I would like it to be faster so returning the function will give a decent performance boost. Note: this is a MRE


Solution

  • Ok, I don't see why you can't just make a list of the functions to be applied at the time get_function() is called. You have all the information about those at that time.

    The only thing missing is the values of the parameters, which are given later.

    from operator import mul
    from operator import truediv as div
    
    def get_function(function_params):
        funcs = [lambda x,p: pow(x,p),lambda x,p: div(x,p),lambda x,p: mul(x,p)]
        funcs = [funcs[i] for i in function_params]
        def fun(x, params):
            func = x
            for f,p in zip(funcs, params):
                func = f(func, p)
            return func
        return fun
    
    f = get_function([2,2])
    print(f(5,[3,4]))
    

    Output:

    60

    since 60 = (5*3)*4