我正在写一个方法来合并两个数字流,我有两个可选的实现:

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只打印“23”,而merge2生成正确的结果。

最佳答案

您需要生成子枚举器生成的每个项:

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

关于ruby - ruby是否支持递归枚举器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22278126/

10-11 08:43