+ 1
Can anyone explain how this code works?
def add(x, y): return x + y def do_twice(func, x, y): return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b))
4 Answers
+ 4
Which part do you not understand? Did you run it to see what it does? In case you haven't do so in the code playground.
+ 2
Apparently you declared a higher order function, the first parameter takes a function which you declared before it, so what it does is to choose what kind of function it uses, you can even declare a sub(x, y) function to understand it further. However, this is very useful when you need to compare/calculate certain stuff of the same category. đ
+ 2
To build on what was just said, since you don't need to specify return type of a function, you can still see that they return integers whenever they're executed, the function was actually called 3 times, just for the record.
0
Simon Sauter , how does
return func(func(x,y), func(x,y))
takes the values and evaluate?
I mean , from where did this func() came?