TExcelTAD
Home › OCaml › OCaml Tail Recursion

OCaml Tail Recursion

Every ordinary function call uses a little space on the call stack until it returns. A recursive function that calls itself a million times can therefore run out of stack. OCaml solves this with tail calls: a call that is the very last thing a function does reuses the current stack frame, so the recursion runs in constant space, exactly like a loop.

Tail position

A call is in tail position when its result is returned directly, with nothing left to do afterwards.

ocaml
let rec sum lst = match lst with
  | [] -> 0
  | x :: rest -> x + sum rest        (* NOT a tail call: "+" still has to run *)

let rec last lst = match lst with
  | [] -> None
  | [ x ] -> Some x
  | _ :: rest -> last rest            (* tail call: its result is returned as is *)

The accumulator pattern

To make a function tail-recursive, carry the partial result in an extra accumulator parameter. Usually you hide this in a local helper:

ocaml · try it yourself
let sum lst =
  let rec go acc = function
    | [] -> acc
    | x :: rest -> go (acc + x) rest     (* tail call *)
  in
  go 0 lst

let () =
  let big = List.init 1_000_000 (fun i -> i + 1) in
  Printf.printf "%d\n" (sum big)
500000500000

(function is shorthand for fun x -> match x with, very common in helpers like this.)

Here is how the accumulator evolves for sum [3; 5; 2]:

text
go 0  [3; 5; 2]
go 3  [5; 2]
go 8  [2]
go 10 []
= 10

There is never more than one active call: each step replaces the previous one.

Fast Fibonacci

The naive fib from the previous lesson makes an exponential number of calls. With two accumulators (the current and next Fibonacci numbers) it becomes a simple loop:

ocaml · try it yourself
let fib n =
  let rec go a b k = if k = 0 then a else go b (a + b) (k - 1) in
  go 0 1 n

let () =
  List.iter (fun n -> Printf.printf "fib %d = %d\n" n (fib n)) [ 10; 50; 90 ]
fib 10 = 55
fib 50 = 12586269025
fib 90 = 2880067194370816120

fib 90 takes 90 steps instead of trillions of calls.

Building lists with an accumulator

When you build a list in an accumulator, elements come out in reverse order, because each new element is added to the front with ::. Reverse once at the end:

ocaml · try it yourself
let squares_upto n =
  let rec go acc i = if i > n then List.rev acc else go ((i * i) :: acc) (i + 1) in
  go [] 1

let () =
  squares_upto 8 |> List.iter (Printf.printf "%d ");
  print_newline ()
1 4 9 16 25 36 49 64 

Stack depth in OCaml 5

OCaml 5 grows the system stack on demand, so even non-tail-recursive functions can go much deeper than in older versions (the default limit is about 1 GB of stack). Deep non-tail recursion still costs memory proportional to its depth, and tail recursion is still the idiomatic choice for long loops:

ocaml · try it yourself
let rec count_down n = if n = 0 then "done" else count_down (n - 1)
let rec sum_to n = if n = 0 then 0 else n + sum_to (n - 1)

let () =
  print_endline (count_down 100_000_000);      (* tail-recursive: constant stack *)
  Printf.printf "%d\n" (sum_to 1_000_000)      (* not tail-recursive: 1 million frames *)
done
500000500000

Which standard functions are tail-recursive?

Most of the List module is tail-recursive in OCaml 5 (List.map, List.append, List.init and List.rev included). List.fold_left is tail-recursive, but List.fold_right is not, so prefer fold_left for long lists.

Tip: The [@tailcall] attribute asks the compiler to warn when a call you believe is a tail call is not: go (acc + x) rest [@tailcall].

Test yourself

Is the recursive call tail-recursive in x + sum rest?

  1. Yes
  2. No, because the addition happens after the call returns
  3. Only for short lists
  4. Only with let rec

What is the usual technique for turning a recursive function into a tail-recursive one?

  1. Use a while loop
  2. Add an accumulator parameter
  3. Use fold_right
  4. Add type annotations

Why is List.rev often called at the end of an accumulator-based list builder?

  1. To sort the list
  2. Because consing onto the accumulator builds the list in reverse
  3. To copy the list
  4. It is required for tail calls