+ 3

# Example in Functional Programming, 1/3

Hi everyone, So, this lesson starts off by giving this example: def apply_twice(func, arg): return func(func(arg)) def add_five(x): return x + 5 print(apply_twice(add_five, 10)) and that gives a result of 20. I don't understand how 20 is the result of calling the function twice? The function add_five takes the root argument, which is 10, and adds 5 to that...so we've got 15 so far...then that function is doubled by apply_twice. So if anything, shouldn't the result be 30? Thanks!

30th Jul 2017, 4:34 AM
creslin_black
+ 7
apply_twice function returns func(func(arg)) where func is add_five. So, when 10 is passed as arg, 5 gets added twice 10+5+5=20
30th Jul 2017, 4:41 AM
Pixie
+ 6
It doesnt work like that. () is for the function call. Not for multiplication π
30th Jul 2017, 4:49 AM
Pixie
+ 3
In this example function apply_twice returns add_five(add_five(10)). That means first time function add_five takes 10 and adds 5, so you have add_five(15). After that second time function add_five takes 15 and adds 5, so finally you have 20 as output.
30th Jul 2017, 4:46 AM
ΠΠ»Π΅ΠΊΡΠ°Π½Π΄Ρ ΠΡΠΎΠΌΠΎΠ·ΠΎΠ½ΠΎΠ²
+ 2
Gotcha, I understand now. So, if I hypothetically had a third function called multiply_result, it'd layer onto the existing two functions like multiply_result(add_twice(add_five(10))), right? If multiply result were just result*2, then it'd be 10+5, then +5 again for 20, then 20*2 for 40.
30th Jul 2017, 5:00 AM
creslin_black
0
Ah okay, I was playing around with the code, trying different arguments, and I saw it was just adding 5 twice to the root argument, but I guess I didn't understand how it's not multiplied. So, to illustrate what I mean by that, if you had 5(5(5)), that'd be 5(25) or 125. So, using that same logic, this function would look something like 2(10+5(10)), which is completely wrong.
30th Jul 2017, 4:47 AM
creslin_black
0
good
19th Jan 2018, 8:00 AM
Prashant Agrawal