Skip to content

Instantly share code, notes, and snippets.

@luislee818
Created February 10, 2016 22:41
Show Gist options
  • Save luislee818/7093373e64a83ce5807e to your computer and use it in GitHub Desktop.
Save luislee818/7093373e64a83ce5807e to your computer and use it in GitHub Desktop.
Y Combinator
const Y = (f) => {
const something = x => f(v => x(x)(v));
// const something = x => f(x(x)); // actually it's this, but will cause stask overflow
return something(something);
};
const factorial = Y(function f(fac) {
return function almost(n) {
return (n == 0 ? 1 : n * fac(n - 1));
}
});
factorial(5); // 120
// Explanations
// There are two 'proper' factorial functions above.
// One is being referenced by variable factorial, it's the return value of Y(fn), according to Y's definition,
// factorial references to something(something);
// The other is referenced in line 11, fac, it's used in subsequent computations, in line 2, the function passed in as fac is x(x), it
// actually has equivalent of something(something), because x is something.
// Our computation starts with something(something)(5), is equivalent to
// something(something) -> f(v => something(something)(v)) -> f(something(something))
// But why something(something) is the key here? It looks weird.
const Y = (f) => {
const something = function something(x) {
return f(function another_fac(v) {
return x(x)(v) ;
});
};
return something(something);
};
const factorial = Y(function f(fac) {
return function almost(n) {
return (n == 0 ? 1 : n * fac(n - 1));
}
});
factorial(5); // 120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment