Created
February 22, 2012 23:21
-
-
Save munro/1888313 to your computer and use it in GitHub Desktop.
Tail Call Optimization
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
// http://paulbutler.org/archives/tail-recursion-in-python/ | |
function tailCall(fn) { | |
return function () { | |
fn = fn.apply(this, arguments); | |
while (typeof fn === 'function') { | |
fn = fn(); | |
} | |
return fn; | |
}; | |
} | |
var tailEven, | |
tailOdd; | |
tailEven = function (x) { | |
if (x === 0) { | |
return true; | |
} else { | |
return function () { | |
return tailOdd(x - 1); | |
}; | |
} | |
}; | |
tailOdd = function (x) { | |
if (x === 0) { | |
return false; | |
} else { | |
return function () { | |
return tailEven(x - 1); | |
}; | |
} | |
}; | |
var even = tailCall(tailEven); | |
var odd = tailCall(tailOdd); | |
console.log(even(100)); | |
console.log(odd(100)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment