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

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

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