Skip to content
Advertisement

python higher order functions: how do i read the code step by step?

I am currently trying to interpret the code but i cant seem to visualise it even when i use python tutor.

def two(f):
    return lambda x: f(f(x))

def three(f):
    return lambda x: f(f(f(x)))

print(three(two(lambda x: x+5))(2))
print(three(two)(lambda x: x+5)(2))

For the first print output, I interpreted it this way: two(two(two(x+5))) = (x + 5 + 5) + (5 + 5) + (5 + 5) = 32

Did I interpret it correctly?

Also, I don’t really know how to interpret the second print output.

Advertisement

Answer

two(f) returns a function that applies f twice, and three(f) returns a function that applies f three times.

If f is a function that adds 5, then three(two(f)) is a function that adds 5 six times (3 * 2 = 6). three(two(f))(2) == 32, so you got the right answer, but I think you got it the wrong way.

three(two), however, is a function that applies two three times, so three(two)(f) == two(two(two(f))). two(f) adds 5 two times. two(two(f)) adds 5 four times. two(two(two(f)))) adds 5 eight times, so three(two)(f)(2) is 2 + 5 * 8 = 42.

Functions like these are actually a very important part of the development of computing. They are known as Church numerals, and this question demonstrates how to do multiplication and exponentiation with them.

Advertisement