Functional Programming | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Functional Programming

Please help! I get stuck in this section: def apply_twice(func, arg): return func(func(arg)) def add_five(x): return x + 5 print(apply_twice(add_five, 10)) I know that the apply_twice takes the add_five func as its argument but i still don't understand how it works. Could anyone describe it more precisely? Thanks a lot!

8th Oct 2017, 7:09 AM
hieu dotrong
hieu dotrong - avatar
2 Answers
+ 2
So let's break it down: the function apply_twice takes two arguments: one called "func" and another called "arg". Of course, we could have named these arguement anything. The reason it applies whatever function it's given twice is because it uses "func" twice. So, in this example, we're using "add_five" as the argument for "func", correct? add_five(10) would give us 15, right? But pay close attention to how the function is set up: return func(func(arg)) // Notice how we use the func arguement twice. That esentially would equate to: return add_five(add_five(10)) Does that make sense? The apply_twice function calls whatever function it's given as it's first arguement (func), and then calls it AGAIN inside that same function. So let's make up a new function: def triple(x): return x * 3 Then we pass this function as an argument to apply_twice: print(apply_twice(triple, 4)) And so essentially this is what "apply_twice" would be doing: return triple(triple(4)) And so we'd get 36 with my "triple" function. Starting from the innermost function, and working it's way out. Here's what a apply_three_times function may look like: def apply_three_times(func, arg): return func(func(func(arg)))
8th Oct 2017, 7:32 AM
Christian Barraza
Christian Barraza - avatar
0
I start getting an idea. Thanks a lot for the help!
31st Oct 2017, 8:56 AM
hieu dotrong
hieu dotrong - avatar