Skip to content

Instantly share code, notes, and snippets.

@rightfold
Last active August 29, 2015 14:09
Show Gist options
  • Save rightfold/0d16ff420aac25fbe3be to your computer and use it in GitHub Desktop.
Save rightfold/0d16ff420aac25fbe3be to your computer and use it in GitHub Desktop.
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