Skip to content

Instantly share code, notes, and snippets.

@voila
Created July 3, 2019 22:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save voila/7243e7c1a856a3c47074f12413b2fa9c to your computer and use it in GitHub Desktop.
Factorial recursive to iterative
let fact0 = (n) => {
if (n > 0) {
return n * fact0(n - 1);
} else
return 1;
}
console.log(fact0(5, (x) => x))
let fact1 = (n, k) => {
if (n > 0) {
return fact1(n - 1, (x) => k(n * x))
} else {
return k(1)
}
}
console.log(fact1(5, (x) => x))
// type cont = {n:int , k:cont} | null
let fact2 = (n, k) => {
let res = 1;
while (true) {
if (n > 0) {
k = { n: n, next: k }; // new cont (stack push)
n = n - 1;
} else {
if (k != null) {
res = res * k.n;
k = k.next; // (stack pop)
}
else
return res;
}
}
}
console.log(fact2(5, null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment