Skip to content

Instantly share code, notes, and snippets.

@mattneary
Created October 4, 2012 00:52
Show Gist options
  • Save mattneary/3830868 to your computer and use it in GitHub Desktop.
Save mattneary/3830868 to your computer and use it in GitHub Desktop.
Y Combinator
In Lambda Calculus, the Y combinator is
Y = (λf . (λx . f (x x)) (λx . f (x x)))
Thus Y(g) would break down like so:
{(x) -> g (x x)} {(x) -> g (x x)}
g( {(x) -> g (x x)} {(x) -> g (x x)} )
g( g ({(x) -> g (x x)} {(x) -> g (x x)}) )
etc...
The Y Combinator finds fixed points, points where f(x) = x. Once found:
f({(v) -> x(x)(v)}) becomes f({(v) -> f(f)(v)}) = f(f)
Y = function(f) {
var f_xx = function(x) {
return f(function(v) { return x(x)(v); });
};
return f_xx(f_xx);
};
var factorial = Y(function(self) {
return function(n) {
return n == 0 ? 1 : n*self(n - 1);
};
});
console.log(factorial(3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment