Look-ahead iterator

If I write a tail recursive function which traverses a list, the each iteration of the function is allowed to look-ahead in the list, so i can make decisions based not only on the current iteration value, but also on the future. However, if I use a simple iterator, this look-into-the-future capability is lost.

Is there a happy medium data structure which is 1) lazy like an iterator but 2) gives some capability to look into the future multiple times?

I found the buffered iterator. This seems to be a step in the director I’m asking for, with the limitation that I can only look-ahead by 1. Also from what I gather, there is no pattern matching interface similar to a List

bufferedIterator match {
  case head::_ => ...
  case Nil => ...
}

This sounds like you want a LazyList (Scala 2.13) or a Stream (older Scala versions).

In both cases you can pattern match like with a List (using #:: instead of ::).

Yes streams. I remember looking at Streams a bit in the Corsera Scala course. But I recall that I didn’t understand them at that time. I managed to work the exercises by trial and error. Kept changing the code until the tests passed. :frowning: nevertheless it was clear that it was a powerful concept.

If you use Stream or LazyList instead of Iterator then there’s potential for memory leak as Stream and LazyList memoize contents. There may be some memory leak bugs in Scala’s stdlib or you can have some unneded references to Stream/ LazyList beginning.

A simple solution is to use using Iterator.sliding(2) to create (essentially) pairs of successive elements, and working with those. Basically this groups each element with the “next” element.

Brian Maso

1 Like