suburbia

Premshree's (品速力) Personal Weblog

etc.

Unmemoize
suburbia
[info]premshree

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.


Memoize
suburbia
[info]premshree

MJD was talking about Memoize. Here it is in Ruby:

module Memoize
  def memoize(func_name)
    cache = {}
    (class<<elf; self; end).send(:define_method, func_name) { |*args| 
      return cache[args] if cache.has_key? args
      cache[args] = super     
    }       
  end     
end

There’s a lot of code in the Perl Memoize module; maybe it does other things—I haven’t really looked. Oh, and here’s this Memoize module from RAA. I’m some months late. :-)

Here’s some pictures from Portland.