Created
September 29, 2011 18:42
-
-
Save Incognito/1251549 to your computer and use it in GitHub Desktop.
My Y-Combinator example
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
/* | |
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