1.使用||延迟初始化
def fib(n)
@result ||= []
return n if (0..1).include? n
@result[n] ||= fib(n-1) + fib(n-1)
end
2.使用无穷大Inifinity
Ruby可以使用无穷大:
irb(main):001:0> Inf = 1 / 0.0
=> Infinity
irb(main):002:0> (-Inf..Inf).include?(10)
=> true
使用Inifinity可以构造无穷大小的Lazy List:
lazyList = (0..1/0.0)
lazyList.take(100).select{|i| i % 2 == 0}
lazyList.take(100).select{rand > 0.9}
3.使用Enumerator:
fib = Enumerator.new { |y|
a = b = 1
loop {
y << a
a, b = b, a + b
}
}
fib.take(10) #=> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
natural_numbers = Enumerator.new do |yielder|
number = 1
loop do
yielder.yield number
number += 1
end
end
#lazy select
class Enumerator
def lazy_select(&block)
Enumerator.new do |yielder|
self.each do |val|
yielder.yield(val) if block.call(val)
end
end
end
end
p natural_numbers
.lazy_select {|n| n % 47 == 0}
.lazy_select {|n| palindrome_number?(n)}
.first(5)
4.使用Fiber:
fib = Fiber.new do
f1 = f2 = 1
loop do
Fiber.yield f1
f1, f2 = f2, f1 + f2
end
end
10.times { puts fib.resume }
参考:
Lazy Enumerators in Ruby