August 1st, 2006
Unmemoize
I tried to add an unmemoize function to the memoize module I talked about earlier:
module Memoize
def memoize(func_name)
cache = {}
(class<<self; self; end).send(:define_method, "#{func_name}u", method(func_name).clone)
(class<<self; self; end).send(:define_method, func_name) do |*args|
return cache[args] if cache.has_key? args
cache[args] = super
end
end
def unmemoize(func_name)
(class<<self; self; end).send(:define_method, func_name) do |*args|
eval(func_name.to_s+"u(#{args})")
end
end
end
So now you can memoize a function and then, at a later point, unmemoize:
def fib(n) return n if n < 2 fib(n-1) + fib(n-2) end include Memoize memoize(:fib) ... fib(15) ... unmemoize(:fib) ... fib(15) ...
It works — in that the function actually unmemoizes, but the function takes noticeably longer than the original function. There’s definitely something I’m not doing right — I don’t know what though.
Anyway, it’s been a long and tiring day. Later.
Posted at 01:23 am | Link
| 11 comments | Leave a comment



