1

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?

3
  • 2
    I actually think that's kind of the purpose of iterators in the first place :D So I'd use iterable1.iterator ++ iterable2.iterator to avoid computation. Commented Mar 7, 2017 at 14:16
  • well, that is the backup plan Commented Mar 7, 2017 at 14:20
  • If you already have Iterable, than you've already calculated your nested values. It's not the chaining that is causing the caculations. Commented Mar 7, 2017 at 14:38

2 Answers 2

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(...)
Sign up to request clarification or add additional context in comments.

2 Comments

So, I should basically use iterable.view to get desired behaviour?
@ayvango Yes, I think so. Or iterable.iterator. Documentation says that "all views for iterable collections are defined by re-interpreting the iterator method".
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.