I encountered the following code when I was doing my assignment. I can understand why the the expression (thrice(add1))(0)
evaluates to 4. If we define f(x) = x + 1
, (thrice(add1))(0)
would be evaluated as f(f(f(x)))
which is ((x+1)+1)+1
. However, I don't quite understand why ((thrice(thrice))(add1))(0)
would evaluate to 27
, instead of 3*3=9
.
//Javascript
function thrice(f) {
return compose(compose(f, f), f);
}
function compose(fun,fun2) {
return function (n) {
return fun(fun2(n));
};
}
function add1(k) {
return k + 1;
}
console.log(((thrice(thrice))(add1))(0)); //27
console.log((thrice(add1))(0)); //3
Inner (thrice):
thrice(1) returns ---> function (n) { return fun(fun2(n));
Outer (thrice):
thrice(1) returns ---> function (n) { return fun(fun2(n));
thrice(1) returns ---> function (n) { return fun(fun2(n));
thrice(1) returns ---> function (n) { return fun(fun2(n));
Outer (add1) introduces the add1 function to the scope.
When the 0's declared, add1 inserts it as k. The add1 function resolves.
K's now one. We're now back into the original ()'s. The variable n's now equal to one.
The function2 or (fun2) becomes add1.
Then outer 'fun' becomes add1.
The whole return of one thrice=3.
The first time the outer thrice happens, the inner thrice returns the three.
The second time it iterates, it's three * three.
Finally with the last time, it's nine * three.