Strict versus lazy
Consider the operation of zipping up two lists. The zip
method pairs elements from the first list with the elements from the second list. Here is a sample run:
scala> List(1,2,3).zip(List(4,5,6,7)) res8: List[(Int, Int)] = List((1,4), (2,5), (3,6)) scala> List(1,2,3).zip(Nil) res9: List[(Int, Nothing)] = List()
All the elements of both the lists are visited to create a zipped list. The following figure shows the zip
operation in action:
As another example of strict evaluation, consider the reverse
method of List
:
scala> List(1,2,3).reverse res11: List[Int] = List(3, 2, 1)
The reverse
method also visits all the elements of the list. ...
Get Learning Functional Data Structures and Algorithms now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.