Tail recursion

A recursive method that calls itself as its last action uses one stack frame per call, and a loop written that way over a large list runs out of stack. A tail-recursive method does not: the compiler turns the call into a jump, and @tailrec makes it refuse the file if the call is not in tail position.

The accumulator

The move from recursion to tail recursion is an accumulator: the partial result travels in a parameter instead of waiting in the caller. The inner method is annotated and the outer one hides the starting value:

tailrec.scala

import scala.annotation.tailrec def factorial(n: BigInt): BigInt = @tailrec def loop(current: BigInt, acc: BigInt): BigInt = if current <= 1 then acc else loop(current - 1, acc * current) loop(n, 1) @main def factorialMain(): Unit = println(factorial(5)) println(factorial(20))

scala-cli run --server=false tailrec.scala

120
2432902008176640000

loop(current - 1, acc * current) is the last expression of its branch, so the compiler reuses the frame; the annotation is checked, not believed. The BigInt result is why 20! prints every digit where an Int would have wrapped.

Over a list

A list is the natural place for the pattern: the empty list ends the recursion and the head and tail take it one step. The sum of a hundred thousand numbers fits in a Long, which is what the accumulator is:

sum.scala

import scala.annotation.tailrec @tailrec def sum(values: List[Int], acc: Long = 0L): Long = values match case Nil => acc case head :: tail => sum(tail, acc + head) @main def sumMain(): Unit = println(sum(List(1, 2, 3, 4))) println(sum((1 to 100_000).toList))

scala-cli run --server=false sum.scala

10
5000050000

case head :: tail matches a non-empty list and names both halves; the two arrows are lined up above because a match reads better that way. A hundred thousand calls are a hundred thousand jumps, and the run finishes in milliseconds.

When the call is not the last one

A method that adds one after the recursive call is not tail recursive, and the annotation refuses it. The compiler says which call and why:

not_tail.scala

import scala.annotation.tailrec @tailrec def length(values: List[Int]): Int = values match case Nil => 0 case _ :: tail => 1 + length(tail) @main def lengthMain(): Unit = println(length(List(1, 2, 3)))

mkdir -p out
scalac -color:never -d out not_tail.scala 2>&1; echo "exit status: $?"

-- Error: not_tail.scala:7:32 --------------------------------------------------
7 | case _ :: tail => 1 + length(tail)
  | ^^^^^^^^^^^^
  | Cannot rewrite recursive call: it is not in tail position
1 error found
exit status: 1

Without the annotation the file compiles and works for a short list, which is the trap: the failure is a StackOverflowError on the one input that is long enough. The fix is the accumulator of the first program, not a bigger stack.

Related

Article author: Arthur Isaev