How to chain Iterable without computing underlying iterators

时光毁灭记忆、已成空白 提交于 2019-12-24 09:52:38

问题


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?

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?


回答1:


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(...)



回答2:


You can code a simple chain-iterable that is a lazy concatenation of Iterable:

case class Chain[A](iter: Iterable[A]*) extends Iterable[A]{
  def iterator: Iterator[A] = iter.map(_.iterator).foldLeft(Iterator.empty: Iterator[A])(_++_)
}

Chain(List(1,2,3), 10 to 15, Vector(42,13))


来源:https://stackoverflow.com/questions/42650334/how-to-chain-iterable-without-computing-underlying-iterators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!