如何制作一个通过其他两个枚举器进行惰性迭代的ruby枚举器? [英] How can I make a ruby enumerator that does lazy iteration through two other enumerators?

查看:82
本文介绍了如何制作一个通过其他两个枚举器进行惰性迭代的ruby枚举器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个枚举器enum1enum2,它们必须延迟进行迭代(因为它们有副作用).我该如何构造第三个枚举器enum3,其中enum3.each{|x| x} lazily 返回enum1 + enum2的等价物?

Let's say I have two enumerators, enum1 and enum2 that must be lazily iterated through (because they have side effects). How do I construct a third enumerator enum3 where enum3.each{|x| x} would lazily return the equivalent of enum1 + enum2?

在我的实际用例中,我正在流式传输两个文件,并且需要流式传输串联.

In my real world use case, I'm streaming in two files, and need to stream out the concatenation.

推荐答案

这似乎正是我想要的;

This seems to work just how I want;

enums.lazy.flat_map{|enum| enum.lazy }

这是示范.定义这些产生副作用的方法;

Here's the demonstration. Define these yielding methods with side-effects;

def test_enum
  return enum_for __method__ unless block_given?
  puts 'hi'
  yield 1
  puts 'hi again'
  yield 2
end  

def test_enum2
  return enum_for __method__ unless block_given?
  puts :a
  yield :a
  puts :b
  yield :b
end  

concated_enum = [test_enum, test_enum2].lazy.flat_map{|en| en.lazy }

然后在结果上调用,表明副作用是懒惰发生的;

Then call next on the result, showing that the side effects happen lazily;

[5] pry(main)> concated_enum.next
hi
=> 1
[6] pry(main)> concated_enum.next
hi again
=> 2

这篇关于如何制作一个通过其他两个枚举器进行惰性迭代的ruby枚举器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆