I was trying to solve "fibonacci" sequence using "Continuation-passing style" in typescript which is a very easy example, but just to try
const cpsFib = (n: number, f: (t: number) => void) => {
if(n === 0 || n === 1) f(1);
else {
cpsFib(n - 1, (t0) => {
cpsFib(n - 2, (t1) => {
f(t0 + t1);
});
})
}
}
const num = 16;
console.time('cps');
const ans = cpsFib(num, (ans) => console.log(`fib(${num}): ${ans}`));
console.timeEnd('cps');
The problem is when I go over 16 as input it causes
Maximum call stack size exceeded
But when I try it with direct style and with providing input more than 40, it works very well
const num = 40;
const fib: (arg: number) => number = (n: number) => n <= 1 ? 1 : fib(n-1)+fib(n-2);
console.log(`fib(${num}): ${fib(num)}`);
so I am trying to get a deep look on why CPS could not solve it with more than 16 while direct styling could.
As I get CPS opens stack in memory for each function passing and direct style opens stack in memory for each function invocation.