Skip to content

Instantly share code, notes, and snippets.

@arjans
Forked from janewang/gist:3259652
Created August 4, 2012 20:16
Show Gist options
  • Save arjans/3259688 to your computer and use it in GitHub Desktop.
Save arjans/3259688 to your computer and use it in GitHub Desktop.
Y Combinator vs. U Combinator vs. Typical Recursion
// 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