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 :: 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)
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 p = 4 :: 5 :: 6 :: Nil p: List[Int] = List(4, 5, 6)
This version, could be rewritten as:
scala> val p = (4 :: (5 :: (6 :: Nil))) p: List[Int] = List(4, 5, 6)
This version, in turn, could be written as:
scala> val p = ( ( (Nil...