1
def compose(f, g):
    return lambda x:f(g(x))

def thrice(f):
    return compose(f, compose(f, f))

add1 = lambda x: x + 1


print(thrice(thrice)(add1)(6)) = 33

Can anyone explain to me why is this 33? which side of the composite function should i start reading?

4
  • Can you explain the assignment in the last line? Commented Feb 6, 2014 at 12:51
  • 3
    This becomes a huge stack expansion.. Commented Feb 6, 2014 at 12:51
  • 3
    The function thrice(thrice) takes a function and returns the same function composited 3^3=27 times. Hence, thrice(thrice)(add1) is a function that adds 27 to its input. Calling it with 6 returns 33. Commented Feb 6, 2014 at 12:56
  • I understand. So we should start reading from the left? Commented Feb 6, 2014 at 13:02

2 Answers 2

1

1) In terms of math, compose(f, g) = f ∘ g

2) Then thrice(f) = f ∘ f ∘ f.

3) Then T := thrice(thrice) = thrice ∘ thrice ∘ thrice

4) Then T(f) = f ∘ f ∘ f ∘ f ∘ f ∘ ... # 27 times

5) Then thrice(thrice)(add1) = T(add1) = add1 ∘ add1 ∘ ... # 27 times

6) Then thrice(thrice(add1))(x) = x + 27

Sign up to request clarification or add additional context in comments.

Comments

0

First call of thrice(thrice) reuturns a function. To that function you pass add1 function and as a result you will again get a function. If you pass 6 to that function you will get 33 as result.

f1 = thrice(thrice)
f2 = f1(add1)
print(f2(6))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.