user3234828
user3234828

Reputation: 59

Explanation of a code

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?

Upvotes: 1

Views: 2890

Answers (2)

JirkaV
JirkaV

Reputation: 1013

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))

Upvotes: 0

bereal
bereal

Reputation: 34312

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

Upvotes: 1

Related Questions