Slide 18
Slide 18 text
LazyLists
A lazy list is a list whose elements are computed lazily. Only those elements requested will be computed. A lazy list can, therefore, be infinitely long. Otherwise,
lazy lists have the same performance characteris4cs as lists. Whereas lists are constructed with the :: operator, lazy lists are constructed with the similar-looking
#:: . Here is a simple example of a lazy list containing the integers 1, 2, and 3:
scala> val str = 1 #:: 2 #:: 3 #:: LazyList.empty
val str: scala.collection.immutable.LazyList[Int] = LazyList()
The head of this lazy list is 1, and the tail of it has 2 and 3. None of the elements are printed here, though,
because the list hasn’t been computed yet! Lazy lists are specified to compute lazily, and the toString
method of a lazy list is careful not to force any extra evalua4on.
Below is a more complex example. It computes a lazy list that contains a Fibonacci sequence star4ng with
the given two numbers. A Fibonacci sequence is one where each element is the sum of the previous two
elements in the series:
scala> def fibFrom(a: Int, b: Int): LazyList[Int] =
a #:: fibFrom(b, a + b)
def fibFrom: (a: Int, b: Int)LazyList[Int]
This func4on is decep4vely simple. The first element of the sequence is clearly a, and the rest of the sequence is the Fibonacci sequence star4ng with b followed
by a + b. The tricky part is compu4ng this sequence without causing an infinite recursion. If the func4on used :: instead of #::, then every call to the func4on
would result in another call, thus causing an infinite recursion. Since it uses #::, though, the right-hand side is not evaluated un4l it is requested.
Here are the first few elements of the Fibonacci sequence star4ng witht two ones:
scala> val fibs = fibFrom(1, 1).take(7)
val fibs: scala.collection.immutable.LazyList[Int] = LazyList()
scala> fibs.toList
val res23: List[Int] = List(1, 1, 2, 3, 5, 8, 13)