0

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.

prathapa reddy
  • 321
  • 1
  • 4
  • 17
  • 1
    The code you showed will throw an error ("None value is not callable"). Generally you call functions by `f(parameters)`. Also note that in python a comment is started by `#`. In python functions are just normal objects, so you can assign them to variables, put them into lists, use them as function parameters, ... so something like the following is well defined: `def call(f, argument): return f(argument)`. – syntonym Jun 17 '16 at 09:07
  • I've edited the code. Sorry for that. – prathapa reddy Jun 17 '16 at 09:09
  • Functions are objects as everything else. They can be passed to functions and returned by functions. For example the `sorted` function takes a `key` argument that is functional: `sorted([1,2,3,4,5,6], key=lambda x: x%2)` will return `[2,4,6,1,3,5]`. – Bakuriu Jun 17 '16 at 09:10

1 Answers1

2

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.

AliciaBytes
  • 7,300
  • 6
  • 36
  • 47