TExcelTAD
Home › OCaml › OCaml Recursion

OCaml Recursion

A recursive function calls itself. In OCaml, recursion is the main way to repeat work: it replaces most loops, and it fits naturally with recursive data such as lists and trees.

let rec

A function can only refer to itself if it is defined with let rec:

ocaml · try it yourself
let rec factorial n =
  if n <= 1 then 1
  else n * factorial (n - 1)

let () =
  for i = 0 to 6 do
    Printf.printf "%d! = %d\n" i (factorial i)
  done
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

Without rec, the name factorial inside the body would refer to an earlier definition (or be unbound), and the compiler reports Unbound value factorial.

Thinking recursively

Every recursive function needs:

  1. A base case that returns without recursing (n <= 1 above).
  2. A recursive case that makes the problem smaller and calls itself (factorial (n - 1)).

Here is how factorial 4 unfolds:

text
factorial 4
= 4 * factorial 3
= 4 * (3 * factorial 2)
= 4 * (3 * (2 * factorial 1))
= 4 * (3 * (2 * 1))
= 24

More examples

ocaml · try it yourself
(* sum of the digits of a non-negative number *)
let rec digit_sum n = if n < 10 then n else (n mod 10) + digit_sum (n / 10)

(* greatest common divisor, Euclid's algorithm *)
let rec gcd a b = if b = 0 then a else gcd b (a mod b)

(* x to the power n, by repeated squaring *)
let rec power x n =
  if n = 0 then 1
  else
    let half = power x (n / 2) in
    if n mod 2 = 0 then half * half else x * half * half

let () =
  Printf.printf "%d\n" (digit_sum 98765);
  Printf.printf "%d\n" (gcd 84 36);
  Printf.printf "%d\n" (power 3 13)
35
12
1594323

Recursion on lists

A list is either empty [] or a head element followed by a tail list, head :: tail. A recursive function handles both cases with match (explained fully in the pattern matching lesson):

ocaml · try it yourself
let rec length lst =
  match lst with
  | [] -> 0
  | _ :: tail -> 1 + length tail

let rec sum lst =
  match lst with
  | [] -> 0
  | head :: tail -> head + sum tail

let () =
  let scores = [ 12; 7; 30; 1 ] in
  Printf.printf "length %d, sum %d\n" (length scores) (sum scores)
length 4, sum 50

Mutual recursion

Two functions that call each other are defined together with let rec ... and ...:

ocaml · try it yourself
let rec is_even n = if n = 0 then true else is_odd (n - 1)
and is_odd n = if n = 0 then false else is_even (n - 1)

let () =
  Printf.printf "%b %b %b\n" (is_even 10) (is_odd 7) (is_even 3)
true true false

Tree-shaped recursion

Some functions call themselves more than once. The classic example is the naive Fibonacci function, which is short but very slow for big n, because it recomputes the same values again and again:

ocaml · try it yourself
let rec fib n = if n < 2 then n else fib (n - 1) + fib (n - 2)

let () =
  List.iter (fun n -> Printf.printf "fib %d = %d\n" n (fib n)) [ 0; 1; 2; 10; 25 ]
fib 0 = 0
fib 1 = 1
fib 2 = 1
fib 10 = 55
fib 25 = 75025

The number of calls grows exponentially. The next lesson shows how to write a fast version with an accumulator.

Warning: A recursive function without a reachable base case runs until the call stack is exhausted. factorial (-1) is safe above only because the base case is n <= 1, not n = 1.

Test yourself

Which keyword allows a function to call itself?

  1. let self
  2. let rec
  3. fun rec
  4. recursive

What is gcd 84 36 with let rec gcd a b = if b = 0 then a else gcd b (a mod b)?

  1. 6
  2. 12
  3. 36
  4. 4

How do you define two functions that call each other?

  1. Define them in any order with let
  2. let rec f ... and g ...
  3. Use let mutual
  4. It is not possible