Ruby Idiom for dynamic programming? (request for comments)

Random idea i had...

I sometimes make custom classes/method for caching output of
functions, i.e. for dynamic programming. To generalise this, i though
it would be possible to implement it like this:

class A
  def func(a, b, *c)
    puts "Computing... #{[a,b,c].inspect}"
    return [a,b,c].hash
  end
  cached :func
end

My 'cached' directive is defined as:

class Module
  def cached(method, cache = (@@funccache ||= {}))
    orig = "uncached_#{method}"
    alias_method orig, method
    define_method method do |*args|
      key = [ method, args ]
      @@funccache[key] ||= send(orig, *args)
    end
  end
end

What's the scope of @@funccache? (What 'object' holds it?). Is there a
better way to do it?

Lars

@@ffunccache is a class variable, not an object variable.
It is shared amongst all instance sof the class Module.

RF

Lars Christensen wrote:

···

Random idea i had...

I sometimes make custom classes/method for caching output of
functions, i.e. for dynamic programming. To generalise this, i though
it would be possible to implement it like this:

class A
  def func(a, b, *c)
    puts "Computing... #{[a,b,c].inspect}"
    return [a,b,c].hash
  end
  cached :func
end

My 'cached' directive is defined as:

class Module
  def cached(method, cache = (@@funccache ||= {}))
    orig = "uncached_#{method}"
    alias_method orig, method
    define_method method do |*args|
      key = [ method, args ]
      @@funccache[key] ||= send(orig, *args)
    end
  end
end

What's the scope of @@funccache? (What 'object' holds it?). Is there a
better way to do it?

Lars

--
Ron Fox
NSCL
Michigan State University
East Lansing, MI 48824-1321

There is memoize already...

Kind regards

robert

···

2008/7/2 Lars Christensen <larsch@belunktum.dk>:

Random idea i had...

I sometimes make custom classes/method for caching output of
functions, i.e. for dynamic programming. To generalise this, i though
it would be possible to implement it like this:

--
use.inject do |as, often| as.you_can - without end

And, since Class is a subclass of Module, ALL classes.

···

On Wed, Jul 2, 2008 at 7:42 AM, Ron Fox <fox@nscl.msu.edu> wrote:

@@ffunccache is a class variable, not an object variable.
It is shared amongst all instance sof the class Module.

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/