Created
September 11, 2012 03:07
-
-
Save michaelfairley/3695645 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 memoize(&blk) | |
cache = {} | |
lambda do |*args| | |
return cache[args] if cache.has_key?(args) | |
cache[args] = blk.call(*args) | |
end | |
end | |
define_singleton_method(:fib, &memoize{ |n| | |
if n < 2 | |
n | |
else | |
fib(n-2) + fib(n-1) | |
end | |
}) | |
puts fib(45) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment