Ruby Idiom for dynamic programming? (request for comments)

  • Thread starter Lars Christensen
  • Start date
L

Lars Christensen

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
 
R

Ron Fox

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

RF

Lars said:
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
 
R

Rick DeNatale

[Note: parts of this message were removed to make it a legal post.]

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


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

Robert Klemme

2008/7/2 Lars Christensen said:
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:

There is memoize already...

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top