TExcelTAD
Home › Scala › Scala Recursion & Tail Recursion

Scala Recursion & Tail Recursion

A recursive function calls itself to solve a smaller version of the same problem. Recursion is the natural way to process recursive data like lists and trees, and it replaces many loops in functional code. Scala adds one important tool: the @tailrec annotation, which guarantees that a recursive function runs in constant stack space.

The shape of a recursive function

Every recursive function needs:

  1. A base case that returns without recursing.
  2. A recursive case that moves closer to the base case.
scala · try it yourself
def countdown(n: Int): Unit =
  if n == 0 then println("Liftoff!")
  else
    println(n)
    countdown(n - 1)

def power(base: Int, exp: Int): Long =
  if exp == 0 then 1
  else base * power(base, exp - 1)

@main def run(): Unit =
  countdown(3)
  println(power(2, 10))
3
2
1
Liftoff!
1024

Recursive methods must declare their return type — the compiler cannot infer it from a definition that refers to itself.

Recursion on lists

Pattern matching with head :: tail pairs perfectly with recursion:

scala · try it yourself
def length[A](xs: List[A]): Int = xs match
  case Nil       => 0
  case _ :: tail => 1 + length(tail)

def reverse[A](xs: List[A]): List[A] = xs match
  case Nil          => Nil
  case head :: tail => reverse(tail) :+ head

def maxOf(xs: List[Int]): Option[Int] = xs match
  case Nil          => None
  case head :: tail => Some(maxOf(tail).fold(head)(m => head.max(m)))

@main def run(): Unit =
  val xs = List(4, 9, 2, 7)
  println(length(xs))
  println(reverse(xs))
  println(maxOf(xs))
  println(maxOf(Nil))
4
List(7, 2, 9, 4)
Some(9)
None

The stack problem

Each non-tail call keeps a frame on the call stack until the inner call returns. With very deep recursion the stack runs out:

scala · try it yourself
def sumTo(n: Int): Long =
  if n == 0 then 0 else n + sumTo(n - 1)   // the + happens AFTER the call returns

@main def run(): Unit =
  println(sumTo(1000))
  try println(sumTo(1_000_000))
  catch case _: StackOverflowError => println("stack overflow!")
500500
stack overflow!

Tail recursion

A call is in tail position when it is the very last thing the function does — nothing is left to compute afterwards. Scala compiles such self-calls into a loop, so they use no extra stack. The trick is to carry the partial result in an accumulator parameter.

scala · try it yourself
import scala.annotation.tailrec

def sumTo(n: Int): Long =
  @tailrec
  def loop(i: Int, acc: Long): Long =
    if i == 0 then acc
    else loop(i - 1, acc + i)       // tail call: nothing left to do afterwards
  loop(n, 0)

@tailrec
def gcd(a: Int, b: Int): Int =
  if b == 0 then a else gcd(b, a % b)

@main def run(): Unit =
  println(sumTo(1_000_000))
  println(gcd(1071, 462))
500000500000
21

@tailrec does not change how the code runs; it asks the compiler to check that the function really is tail-recursive. If it is not, compilation fails with an error such as Cannot rewrite recursive call: it is not in tail position. That turns a potential runtime crash into a compile error.

Converting to tail recursion

Non-tail version Tail-recursive version
n * factorial(n - 1) loop(n - 1, acc * n)
1 + length(tail) loop(tail, count + 1)
reverse(tail) :+ head loop(tail, head :: acc)
scala · try it yourself
import scala.annotation.tailrec

def factorial(n: Int): BigInt =
  @tailrec def loop(k: Int, acc: BigInt): BigInt =
    if k <= 1 then acc else loop(k - 1, acc * k)
  loop(n, 1)

def reverse[A](xs: List[A]): List[A] =
  @tailrec def loop(rest: List[A], acc: List[A]): List[A] = rest match
    case Nil          => acc
    case head :: tail => loop(tail, head :: acc)
  loop(xs, Nil)

@main def run(): Unit =
  println(factorial(20))
  println(factorial(30))
  println(reverse(List("a", "b", "c")))
  println(reverse((1 to 100_000).toList).take(3))
2432902008176640000
265252859812191058636308480000000
List(c, b, a)
List(100000, 99999, 99998)

The accumulator version of reverse is also much faster: head :: acc is constant time, while :+ on a list is linear.

Recursion on trees

Some data is naturally tree-shaped. Recursion that branches into several calls is not tail-recursive, but tree depth is usually small, so that is fine.

scala · try it yourself
enum Tree:
  case Leaf(value: Int)
  case Node(left: Tree, right: Tree)

import Tree.*

def sum(t: Tree): Int = t match
  case Leaf(v)    => v
  case Node(l, r) => sum(l) + sum(r)

def depth(t: Tree): Int = t match
  case Leaf(_)    => 1
  case Node(l, r) => 1 + depth(l).max(depth(r))

@main def run(): Unit =
  val tree = Node(Node(Leaf(1), Leaf(2)), Node(Leaf(3), Node(Leaf(4), Leaf(5))))
  println(sum(tree))
  println(depth(tree))
15
4

Tip: Before writing recursion by hand, check whether a collection method already does the job: sum, foldLeft, reverse, maxOption. Use hand-written recursion for your own recursive data types and algorithms.

Test yourself

What does @tailrec do?

  1. Makes any recursive function faster
  2. Asks the compiler to verify the function is tail-recursive (and fail otherwise)
  3. Caches results
  4. Runs the function in parallel

Is n + sum(n - 1) a tail call?

  1. Yes
  2. No, the addition happens after the recursive call returns
  3. Only for small n
  4. Only with @tailrec

Why must recursive methods declare their return type?

  1. For performance
  2. The compiler cannot infer the type of a method that refers to itself
  3. It is only a style rule
  4. So they can be @tailrec