-
-
Save rightfold/0d16ff420aac25fbe3be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Thunk(f) { | |
this.f = f; | |
} | |
function trampoline(f) { | |
return function() { | |
var result = f.apply(this, arguments); | |
while (result instanceof Thunk) { | |
result = result.f(); | |
} | |
return result; | |
}; | |
} | |
function factorial(n) { | |
var _factorial = trampoline(function self(acc, n) { | |
if (n > 0) { | |
return new Thunk(function() { return self(acc * n, n - 1); }); | |
} else { | |
return acc; | |
} | |
}); | |
return _factorial(1, n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment