Created
August 4, 2012 20:54
-
-
Save arjans/3259868 to your computer and use it in GitHub Desktop.
Recursive and Memoized Y-Combinator Fibonacci Functions
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
//Recursive fibonacci | |
var fib_recur = function (n) { | |
if (n == 0) return 0 ; | |
if (n == 1) return 1 ; | |
return fib_recur(n-1) + fib_recur(n-2) ; | |
} ; | |
//Recursive fibonacci with memoization (but without the Y-Combinator) | |
var fibonacci = (function ( ) { | |
var memo = [0, 1]; | |
var fib = function (n) { | |
var result = memo[n]; | |
if (typeof result !== 'number') { | |
result = fib(n − 1) + fib(n − 2); | |
memo[n] = result; | |
} | |
return result; | |
}; | |
return fib; | |
}( )); | |
// 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) ; | |
}) ; }) ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment