Created
August 4, 2012 20:07
-
-
Save janewang/3259652 to your computer and use it in GitHub Desktop.
Y Combinator (standard and recursive) 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 | |
var Y = function (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_recursive = function (f) { | |
return f(function(x) { | |
return Y_recursive(f)(x); | |
}); | |
}; | |
var Y_factorial_recursive = Y_recursive(function (f) { | |
return function (n) { | |
if (n == 0) { return 1; } | |
else { return n * f(n - 1); } | |
}; | |
}); | |
//--------------------------------------------------------------------- | |
// U combinator | |
var U = function (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)); | |
} | |
} | |
}); | |
//------------------------------------------------------------------- | |
// standard 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); | |
Recursive and Memoized Y-Combinator Fibonnaci Functions: https://gist.github.com/3259869 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment