Skip to content

Instantly share code, notes, and snippets.

@gerardpaapu
Forked from fitzgen/gist:749904
Last active December 11, 2015 02:09
Show Gist options
  • Save gerardpaapu/4528317 to your computer and use it in GitHub Desktop.
Save gerardpaapu/4528317 to your computer and use it in GitHub Desktop.
(function () {
// conceal the Thunk class to avoid
// so that the only way to make one is
// to call Function::thunk
function Thunk(fn, args) {
this.fn = fn;
this.args = args;
}
Thunk.prototype.force = function () {
return this.fn.apply(null, this.args);
};
Function.prototype.thunk = function () {
return new Thunk(this, arguments);
};
Function.prototype.trampoline = function () {
var thunk = new Thunk(this, arguments);
while (thunk instanceof Thunk){
thunk = thunk.force();
}
return thunk;
};
}());
function even(n){
return n == 0 ? true
: odd.thunk(n - 1);
};
function odd(n){
return n == 0 ? false
: even.thunk(n - 1);
};
console.log(even.trampoline(100001));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment