O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required