Skip to content

Instantly share code, notes, and snippets.

@ariellephan
Last active August 17, 2016 19:37
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 ariellephan/7502ccfd6b986e0861bd87471a06879e to your computer and use it in GitHub Desktop.
Save ariellephan/7502ccfd6b986e0861bd87471a06879e to your computer and use it in GitHub Desktop.
Y Combinator in js
// Credits: http://matt.might.net/articles/implementation-of-recursive-fixed-point-y-combinator-in-javascript-for-memoization/
// Ymem takes a functional and an (optional)
// cache of answers.
// It returns the fixed point of the functional
// that caches intermediate results.
function Ymem(F, cache) {
if (!cache)
cache = {} ; // Create a new cache.
return function(arg) {
if (cache[arg])
return cache[arg] ; // Answer in cache.
var answer = (F(function(n){
return (Ymem(F,cache))(n);
}))(arg) ; // Compute the answer.
cache[arg] = answer ; // Cache the answer.
return answer ;
} ;
}
var fib = Ymem(function (g) { return (function (n) {
if (n == 0) return 0 ;
if (n == 1) return 1 ;
return g(n-1) + g(n-2) ;
}) ; }) ;
console.log(fib(100)) ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment