Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Created March 6, 2016 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hunan-rostomyan/75d1fa63665fe94a8902 to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/75d1fa63665fe94a8902 to your computer and use it in GitHub Desktop.
Defining Recursive Functions using a Fixed Point Combinator
/* A fixed point combinator */
function fix(f) {
var g = function(x){return f(function(y){return x(x)(y);});};
return g(g);
}
/* An indirectly recursive factorial function. */
function factorial(self) {
return function(n) {
if (n == 0) {return 1;}
return n * self(n - 1);
};
};
/* By fixing `factorial` we supply it as an argument
to itself, so that by making calls to `self`, `factorial`
can indirectly call itself. */
var fact = fix(factorial);
/* The behavior is what we would expect. */
fact(3); //=> 6
fact(5); //=> 120
fact(9); //=> 362880
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment