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

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.