Iterators, LazyLists and views

A transformation on a list builds a new list, even when the program needs only the first element of the result. The lazy forms avoid that: an Iterator hands out its elements one at a time, a LazyList is a list whose tail is computed when it is first read and then kept, and a view makes a strict collection behave lazily for one pipeline.

An iterator is read once

An iterator has a next and a hasNext, and the transformations keep it lazy: map on an iterator runs as the values are pulled, and take stops the source. An iterator over an infinite sequence is therefore usable as long as something bounds it:

iterators.scala

@main def iterators(): Unit = val it = Iterator(1, 2, 3, 4) println(it.next()) println(it.hasNext) println(it.toList) println(Iterator.from(1).map(_ * 2).filter(_ % 3 == 0).take(4).toList) println(Iterator.iterate(1)(_ * 2).take(6).toList) println(Iterator(1, 2, 3).zip(Iterator("a", "b")).toList) val (evens, odds) = Iterator(1, 2, 3, 4).partition(_ % 2 == 0) println(evens.toList) println(odds.toList)

scala-cli run --server=false iterators.scala

1
true
List(2, 3, 4)
List(6, 12, 18, 24)
List(1, 2, 4, 8, 16, 32)
List((1,a), (2,b))
List(2, 4)
List(1, 3)

Iterator.from(1) never ends, and the pipeline takes four values from it, so the millionth element is never generated. An iterator cannot be walked twice: toList consumes it, and a program that needs the elements again keeps that list. A collection is the safer value to pass around for that reason: it can be read as often as the code likes.

LazyList and view

A LazyList is a sequence like a list, except that its tail is a thunk: the elements are computed when they are first needed and remembered afterwards. A counter counts the calls to show when the work happens for each of the three forms:

laziness.scala

@main def laziness(): Unit = var evaluations = 0 val squares = LazyList.from(1).map { n => evaluations += 1 n * n } println(squares.take(3).toList) println(evaluations) println(squares.take(5).toList) println(evaluations) val strict = (1 to 5).map { n => evaluations += 1 n * 2 } println(strict.toList) println(evaluations) val viewed = (1 to 5).view.map { n => evaluations += 1 n * 3 } println(viewed.take(2).toList) println(evaluations) println(LazyList.continually(7).take(4).toList)

scala-cli run --server=false laziness.scala

List(1, 4, 9)
3
List(1, 4, 9, 16, 25)
5
List(2, 4, 6, 8, 10)
10
List(3, 6)
12
List(7, 7, 7, 7)

take(3) evaluates three squares, and take(5) evaluates two more because the first three are already there. The strict map over 1 to 5 runs all five at once, and the view runs two, because take(2) asks for two. That is the choice: a LazyList for a sequence that is read more than once and may be infinite, an Iterator for a stream that is read once, and a view for one pipeline over an existing collection.

Related

Автор статьи: Arthur Isaev