Skip to content

Instantly share code, notes, and snippets.

@robdodson
Created August 31, 2012 20:21
Show Gist options
  • Select an option

  • Save robdodson/3558423 to your computer and use it in GitHub Desktop.

Select an option

Save robdodson/3558423 to your computer and use it in GitHub Desktop.
y combinator
/**
* Creates a recursive function from one that isn't
* @param {Function} x A non-recursing function
* @return {Function} A recursive version of x
*/
function yCombinator(x) {
return (function(procedure) {
return x(function(arg) {
return procedure(procedure)(arg);
});
})(function(procedure) {
return x(function(arg) {
return procedure(procedure)(arg);
});
});
}
// Usage
var factorial = yCombinator(function(recurse) {
return function(x) {
return x === 0 ? 1 : x * recurse(x - 1);
};
});
var result = factorial(6);
console.log(result); // logs 720
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment