pythonchained

Python function call example([a,b,c,d])(input)


I'm relatively new to python programming, I saw this code snippet in codewarriors. Can somebody please explain this code...

def example(functions):
  #my_code
  return None

example([a,b,c,d])(input) #What kind of call is this?

Here a,b,c,d are defined functions. I need to define example function to return result same as the result of d(c(b(a(input))))

I'm just familiar with example([1,2,3])(1) Here the passed value is a list. But what if they are functions.

Please also comment any good resources to understand it clearly.


Solution

  • Let's look at what foo(x)(y) usually means:

    def foo(x):
        def bar(y):
            return x + y
        return bar
    
    print(foo(2)(3)) #prints 5
    

    Here the first function call returns another function that then gets called with its own arguments, it can also use the arguments and local variables of the first function.

    In your case what they probably wanted you to write is:

    def example(functions)
    
        def f(input):
            for function in functions:
                input = function(input)
            return result
    
        return f
    

    example(<functionlist>) returns a 2nd function that applies all the functions in <functionlist> to the input passed to the 2nd(returned) function call.