Skip to content

Instantly share code, notes, and snippets.

@Incognito
Created September 29, 2011 18:42
Show Gist options
  • Save Incognito/1251549 to your computer and use it in GitHub Desktop.
Save Incognito/1251549 to your computer and use it in GitHub Desktop.
My Y-Combinator example
/*
First group takes a function and returns a
function that calls a function with an
argument
*/
(function (ycomb) {
return (function(n){
return ycomb(ycomb)(n);
});
/*
Second group is the function passed to the
recursive combinator.
*/
})(function (self) {
/*
This is the part that you're working with
that becomes your recursive function.
*/
return function (x) {
if ( x > 0 ) {
console.log(x);
/*
It's really important that the value you
return is a function that calls it's self
that passes the next set of arguments
*/
return self(self)(x-1);
}
};
/*
And this is your input value
*/
})(5);
/*
Notes: You could always abstract away
most of the ceremony for this, should
you ever need to use a y-combinator I
would advise you do so.
Uses: Really, the only time you're going
to use this is when you're programming
a function that is anonymous and you
cannot expose any variables to a higher
scope.
Warning: Most people will never encounter
this in JavaScript. Also, beware that
Internet Explorer 6, 7, 8 all run
"JScript" not JavaScript, and it will
hoist all anonymous functions into a global
namespace. This is resolved with IE9.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment