December 2015
Intermediate to advanced
298 pages
5h 30m
English
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 ...
Read now
Unlock full access