ruby是否支持递归枚举器?

时间:2014-03-09 03:43:34

标签: ruby

我正在编写一种方法来合并两个数字流,我有两个替代实现:

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会产生正确的结果。

1 个答案:

答案 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