From: Daniel Berger Date: 2006-01-01T21:32:56+09:00 Subject: Re: Memoization, files and Marshal? ara.t.howard@noaa.gov wrote: > On Sun, 1 Jan 2006, Daniel Berger wrote: > > > ara.t.howard@noaa.gov wrote: > >> On Sun, 1 Jan 2006, Daniel Berger wrote: > > > > > > > >> harp:~ > cat a.rb > >> def memoize_to_file(name, file) > >> cache = Hash.new.update(Marshal.load(File.read(file))) rescue {} > >> (class << self; self; end).class_eval do > >> define_method(name) do |*args| > >> unless cache.has_key?(args) > >> cache[args] = method(name).call(*args) > >> File.open(file, "wb+"){|f| Marshal.dump(cache, f) } > >> end > >> cache[args] > >> end > >> end > >> end > >> > >> def fib(n) > >> return n if n < 2 > >> fib(n-1) + fib(n-2) > >> end > >> > >> memoize_to_file "fib", "fib.cache" > >> n = fib 10 > >> p n > > > > As is, I get a stack level too deep error on Windows. If I change the > > "cache[args] =" to "cache[args] ||=", I always get back nil. > > > > I'm probably being thick here, but any help is appreciated. > > sorry, don't know how that's running on linux in the first place... you need: > > --- a.rb 2005-12-31 20:30:59.000000000 -0700 > +++ b.rb 2005-12-31 20:31:10.000000000 -0700 > @@ -1,9 +1,10 @@ > def memoize_to_file(name, file) > + meth = method(name) > cache = Hash.new.update(Marshal.load(File.read(file))) rescue {} > (class << self; self; end).class_eval do > define_method(name) do |*args| > unless cache.has_key?(args) > - cache[args] = method(name).call(*args) > + cache[args] = meth.call(*args) > File.open(file, "wb+"){|f| Marshal.dump(cache, f) } > end > cache[args] > > with that it works for me on linux and windows. > > cheers. > > -a > -- > Thanks, that did the trick nicely. It's now part of memoize 1.2.0. :) Regards, Dan