1

A function fact is defined to find the factorial in a continuation passing style,

    function fact(n,myFun)
    {
       if(n==1)
         myFun(1);
       else
         fact(n-1,function inner(t0){ myFun(n*t0) });
    }

called with,

    fact(4, function outer(k) { console.log(k); } );

Here after using breakpoints I understand that after we call this function, the program executes as

n = 4, fact(4, outer), then

n = 4, fact(3, inner(t0)), then

n = 3, fact(2, inner(t0)), then

n = 2, fact(1,inner(t0)) and then

myFun(1)

I am having trouble understanding after this, how is the 1 value from myFun(1) passed on to t0

Cloverr
  • 208
  • 3
  • 12

1 Answers1

1

You could check whats happen, if you log the function as well.

function fact(n, myFun) {
    console.log(n, myFun);
    if (n == 1) {
        myFun(1);
    } else {
        fact(n - 1, function inner(t0) {
            console.log(n, t0);
            myFun(n * t0);
        });
    }
}

fact(4, function (v) { console.log(v); return v; });
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392