Created
March 7, 2012 01:11
-
-
Save vothane/1990229 to your computer and use it in GitHub Desktop.
YET ANOTHER RUBY IMPLEMENTATION for MEMOIZATION based on James Edward Gray II blog (blog.grayproductions.net/articles/caching_and_memoization), however turned to be more problematic than a solution.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'digest/sha2' | |
require 'base64' | |
class HashClod < Hash | |
def [](key) | |
r = super(key) | |
puts r | |
if r == nil | |
puts "set cache" | |
else | |
puts "get cache" | |
end | |
r | |
end | |
end | |
module YARIM # YET ANOTHER RUBY IMPLEMENTATION for MEMOIZATION | |
def memoize( name, cache = Hash.new ) | |
original = "__unmemoized_#{name}__" | |
([Class, Module].include?(self.class) ? self : self.class).class_eval do | |
alias_method original, name | |
private original | |
define_method(name) do |*args| | |
unique_id = self.generate_id args | |
cache[unique_id] ||= send(original, *args) | |
end | |
end | |
def self.generate_id(*args) | |
args = args[0] | |
args.each do |arg| | |
arg.sort! if arg.instance_of? Array | |
arg.values.sort! if arg.instance_of? Hash | |
end | |
arguments = Marshal::dump args | |
unique_id = Base64::encode64(Digest::SHA256.digest(arguments))[0..12].chomp( "=" ) | |
return unique_id | |
end | |
end | |
def Type(klass = :hash) | |
if klass == :hash | |
Hash | |
else | |
Class.new do | |
def message | |
"place holder go mongodb" | |
end | |
end | |
end | |
end | |
end | |
extend YARIM | |
def add(*args) | |
2 + args.first | |
end | |
memoize :add, HashClod.new | |
add(1) | |
add(1) | |
add(1, 2, 3) | |
add(1, 2, 3) | |
add(4, 3, [2, 3]) | |
add(4, 3, [2, 3]) | |
add(4, 3, [3, 2]) | |
add(6, :a => 1, :b => 3) | |
add(6, :a => 1, :b => 3) | |
add(6, :b => 3, :a => 1) | |
puts "done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment