-
-
Save arjans/3259688 to your computer and use it in GitHub Desktop.
Y Combinator vs. U Combinator vs. Typical Recursion
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
// Y combinator | |
function Y(f) { | |
return ( | |
(function (x) { | |
return f(function (v) { return x(x)(v); }); }) | |
(function (x) { | |
return f(function (v) { return x(x)(v); }); }) | |
); | |
} | |
var Y_factorial = Y(function (f) { | |
return function (n) { | |
if (n == 0) { return 1; } | |
else { return n * f(n - 1); } | |
}; | |
}); | |
//--------------------------------------------------------------------- | |
Y-combinator recursive | |
var Y = function(f) { | |
return f(function(x) { | |
return Y(f)(x); | |
}); | |
}; | |
var Y_factorial = Y(function (f) { | |
return function (n) { | |
if (n == 0) { return 1; } | |
else { return n * f(n - 1); } | |
}; | |
}); | |
//--------------------------------------------------------------------- | |
// U combinator | |
function U(f) { | |
return f(f); | |
}; | |
var U_factorial = U(function (f) { | |
return function (n) { | |
if (n == 0) { | |
return 1; | |
} | |
else { | |
return n*(f(f)(n - 1)); | |
} | |
} | |
}); | |
//------------------------------------------------------------------- | |
// factorial recursion | |
var factorial = function(n) { | |
if(n === 0) { | |
return 1; | |
} else { | |
return n * factorial(n-1); | |
} | |
}; | |
// define omega which is the simplest non-terminating lambda expression | |
// var omega = U(U); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment