我正在编写一种方法来合并两个数字流,我有两个替代实现:
def merge1(l1, l2)
Enumerator.new do |yielder|
h = case l1.peek <=> l2.peek
when -1 then l1.next
when +1 then l2.next
else l1.next; l2.next
end
yielder << h
yielder << merge1(l1, l2).next
end.lazy
end
def merge2(l1, l2)
Enumerator.new do |yielder|
loop do
h = case l1.peek <=> l2.peek
when -1 then l1.next
when +1 then l2.next
else l1.next; l2.next
end
yielder << h
end
end.lazy
end
puts merge2((1..Float::INFINITY).lazy.map {|x| x * 2}, (1..Float::INFINITY).lazy.map {|x| x * 3}).first(10)
但是merge1
只会打印“2 3”,而merge2
会产生正确的结果。
答案 0 :(得分:3)
您需要生成子枚举器生成的每个项目:
def merge1(l1, l2)
Enumerator.new do |yielder|
h = case l1.peek <=> l2.peek
when -1 then l1.next
when +1 then l2.next
else l1.next; l2.next
end
yielder << h
merge1(l1, l2).each do |h| # <----
yielder << h # <----
end # <----
end.lazy
end