Created
February 19, 2010 23:17
-
-
Save adacosta/309341 to your computer and use it in GitHub Desktop.
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
def lambda_mem(f, cache=nil) | |
cache = {} if cache.nil? | |
lambda do |h| | |
return cache[h] if cache[h] | |
cache[h] = f.call( lambda {|n| lambda_mem(f, cache).call(n) } ).call(h) | |
end | |
end | |
def fib(g) | |
raise(ArgumentError, "Argument must be positive") if g < 0 | |
lambda_mem( | |
lambda {|g| lambda {|n| [0,1][n] ? n : g.call(n - 1) + g.call(n - 2) } } | |
).call(g) | |
end | |
puts fib(100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment