如何在不计算底层迭代器的情况下链接Iterable [英] How to chain Iterable without computing underlying iterators

查看:46
本文介绍了如何在不计算底层迭代器的情况下链接Iterable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个迭代器,我可以只编写 iter1 ++ iter2 ,直到需要它们时才计算迭代器.有没有办法以相同的方式链接 Iterable 实例?

If I had two iterators I could just write iter1 ++ iter2 and iterators would not be computed until they are needed. Is there any way to chain Iterable instances in the same way?

我尝试使用 iterable1 ++ iterable2 ,但是它会导致立即计算嵌套值,就像它们被添加到某些结构中一样.是否有可能避免这种额外的计算并创建额外的数据结构?

I tried to use iterable1 ++ iterable2 but it causes immediately calculating nested values just like they are added to some structure. Is it possible to avoid this extra calculations and creating extra data structures?

推荐答案

否. Iterable 只是一个可以由任何可以迭代的东西实现的接口.因此,当您有一个 Iterable [Int] 可以是惰性集合或严格集合时,就无法知道.

No. Iterable is just an interface that can be implemented by anything that can be iterated over. So when you have an Iterable[Int] that can be either a lazy or a strict collection, there's no way to know.

scala> val iterable1: Iterable[Int] = List(1,2,3)
iterable1: Iterable[Int] = List(1, 2, 3)

scala> iterable1 ++ iterable1
res2: Iterable[Int] = List(1, 2, 3, 1, 2, 3)

scala> val iterable2: Iterable[Int] = List(1,2,3).view
iterable2: Iterable[Int] = SeqView(...)

scala> iterable2 ++ iterable2
res3: Iterable[Int] = SeqViewA(...)

这篇关于如何在不计算底层迭代器的情况下链接Iterable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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