Eric M.
Eric M.

Reputation: 662

Prepending to a Scala Iterator -- timeout?

I want to prepend a new iterator to my existing iterator.

  1. How can I prepend a new Iterator to an existing Iterator?

  2. Why does my code cause my REPL to hang?

The following hangs indefinitely in my REPL:

scala> var i = Seq(1).iterator
var i: Iterator[Int] = <iterator>

scala> i = Seq(2).iterator ++ i
// mutated i

scala> i.next()
val res0: Int = 2

scala> i.next()
. . .

Note that the following works, but this is an append not a prepend:

var i = Seq(1).iterator
i = i ++ Seq(2).iterator
i.next()
i.next()

This also works, but materializes the entire iterator which I cannot do:

var i = Seq(1).iterator
i = (Seq(2) ++ i.toSeq).iterator
i.next()
i.next()

Thanks!

Upvotes: 0

Views: 90

Answers (1)

michaJlS
michaJlS

Reputation: 2500

Simply speaking, it hangs because you have there an infinite loop. In the line where you think you are merging iterators, you are actually referencing the new i (laziness) and not the initial value of i.

You can get over that by introducing a new var as Luis Miguel pointed out

var i = Seq(1).iterator
var j = i
i = Seq(2).iterator ++ j
i.next()
i.next()

so that should do the trick. Hope it helps and is clear enough.

Upvotes: 1

Related Questions