Monday, September 26, 2005
Y combinator in Javascript
As you might know the fix point combinator of a function is another function that is left unchanged by further applications of the fix point combinator. This is also known as the Y combinator.
A function, often denoted Y, which computes a fixed point of any function it is given. Y is a function with the property that f(Y(f)) = Y(f) for all functions f.
In JavaScript, it is:
With this, factorial can be defined as:
More info at The Little JavaScripter.
A function, often denoted Y, which computes a fixed point of any function it is given. Y is a function with the property that f(Y(f)) = Y(f) for all functions f.
In JavaScript, it is:
function Y(le) {
return function (f) {
return f(f);
}(function (f) {
return le(function (x) {
return f(f)(x);
});
});
}
With this, factorial can be defined as:
var factorial = Y(function (factorial) {
return function (n) {
return n <= 2 ? n : n * factorial(n - 1);
};
});
var number120 = factorial(5);
More info at The Little JavaScripter.