Created
March 6, 2016 09:02
-
-
Save hunan-rostomyan/75d1fa63665fe94a8902 to your computer and use it in GitHub Desktop.
Defining Recursive Functions using a Fixed Point Combinator
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
/* 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