Infinite sequences – Scala streams

We have seen many examples of Scala's list. Lists are sequences. Moreover, lists are strict sequences. Meaning all elements of the list are constructed upfront. However, there are non-strict sequences, whose elements are constructed as needed.

A list is formed by connecting cons cells. There are two cases:

  1. 1 :: Nil

    In this case, the cons cell has a value and the empty list as a tail. This list has only one element. Let's fire up the REPL and try the following snippets:

    scala> 1 :: Nil
    res2: List[Int] = List(1)
    
  2. 1 :: 2 :: Nil

    Here, we have the cons cell having a value and another list as a tail:

    scala> (1 :: (2 :: Nil)).tail
    res11: List[Int] = List(2)
    

A list with three elements looks like the following:

scala> val ...

Get Scala Functional Programming Patterns 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.