Yet another Ruby Memoization

night_stalker: [url]http://www.iteye.com/topic/406220[/url]
Hooopo: [url]http://www.iteye.com/topic/810957[/url]
两位大仙都讨论过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,[url]http://blog.grayproductions.net/articles/caching_and_memoization[/url]可以专门用作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的博客很不错:
[url]http://blog.grayproductions.net/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值