Yet another Ruby Memoization

night_stalker: http://www.iteye.com/topic/406220
Hooopo: http://www.iteye.com/topic/810957
两位大仙都讨论过Ruby Memoization
首先说一下什么是Memoization:
举个例子,fib数列:
def fib(n)
  return n if (0..1).include? n
  fib(n-1) + fib(n-2)
end

递归调用,有很多重复的计算,如果我们能够将计算过的结果保存下来,下一次
需要计算的时候,直接出结果就ok了,这就是动态规划的思想。
于是乎:
def fib(n)
     @result ||= []
     return n if (0..1).include? n
     @result[n] ||= fib(n-1) + fib(n-1)
end

我们使用一个@result数组来保存已经计算的结果,并且如果计算过直接返回。
||=是Ruby作为Lazy init和cache的惯用法。
但是对于false和nil的结果,由于||的特性,无效:
def may_i_use_qq_when_i_have_installed_360?
  @result ||= begin
     puts "我们做出了一个艰难的决定..."
     false
  end
end

每次都的做出艰难的决定...
James 写了一个module, http://blog.grayproductions.net/articles/caching_and_memoization可以专门用作Memoization
代码类似如下:
module Memoizable
    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) { |*args| cache[args] ||= send(original, *args) }
        end
    end
end

使用这个模块,我们只需要include这个module,然后memoize :meth即可
include Memoizable

def fib(n)
    return n if (0..1).include? n
    fib(n-1) + fib(n-2)
end

memoize :fib

可以使用
module Functional
  #
  # Return a new lambda that caches the results of this function and 
  # only calls the function when new arguments are supplied.
  #
  def memoize
    cache = {}  # An empty cache. The lambda captures this in its closure.
    lambda {|*args|
      # notice that the hash key is the entire array of arguments!
      unless cache.has_key?(args)  # If no cached result for these args
        cache[args] = self[*args]  # Compute and cache the result
      end
      cache[args]                  # Return result from cache
    }
  end
  # A (probably unnecessary) unary + operator for memoization
  # Mnemonic: the + operator means "improved"
  alias +@ memoize        # cached_f = +f
end

class Proc; include Functional; end
class Method; include Functional; end

这样:
factorial = lambda {|x| return 1 if x==0; x*factorial[x-1]; }.memoize
# Or, using the unary operator syntax
factorial = +lambda {|x| return 1 if x==0; x*factorial[x-1]; }





James的博客很不错:
http://blog.grayproductions.net/

你可能感兴趣的:(.net,qq,cache,Ruby,360)