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 the lazy list by placing a recursive call to the method, s
.
However, the following form is a succinct one:
scala> def succ(n: Int):Stream[Int] = n #:: succ(n+1) succ: (n: Int)Stream[Int] scala> lazy val r...