Recursive streams

We looked at recursion earlier. Recursive forms are defined in terms of themselves. For example, folders can have subfolders, which, in turn, can have subfolders themselves. Another example is recursive methods calling themselves.

We can use a similar form to define recursive streams. To define recursive streams, consider the following case:

scala> lazy val r = Stream.cons(1, Stream.cons(2, Stream.empty)) 
r: Stream.Cons[Int] = <lazy> 
scala> (r take 4) foreach {x => println(x)} 
1
2

How is this useful? The second cons call can be recursive. (Note we don't need any var):

scala> def s(n: Int):Stream[Int]  = 
     |   Stream.cons(n, s(n+1))  // 1
s: (n: Int)Stream[Int] 
scala> lazy val q = s(0) 
q: Stream[Int] = <lazy> 

Here, we construct ...

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.