Two forms of recursion
In the previous sections, we saw the tail recursive code to reverse a list. Take a look at this form:
object ReverseAList1 extends App { def reverseList(list: List[Int]): List[Int] = list match { case head :: tail => reverseList(tail) :+ head case Nil => Nil } val l = (1 to 20000).toList println(reverseList(l)) }
I know. This form is not tail recursive. Hence, this form will not benefit from the tail call optimization. Try to put the @tailrec
annotation on the reverseList
method. You will get a compilation error.
This form is still useful though. There are times when we do not want all the list elements. We just want to look at the first few elements of the result. We want to make the recursive call evaluation deferred. Call is not computed upfront. Instead, it is only evaluated when needed. We are talking of delayed evaluation in this case. Scala's Streams implements lazy lists where elements are only evaluated when they are needed. We will look in detail...