Last active
August 17, 2016 19:37
-
-
Save ariellephan/7502ccfd6b986e0861bd87471a06879e to your computer and use it in GitHub Desktop.
Y Combinator in js
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
// 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