Recursion in OCaml

Our example demonstrates recursive functions in OCaml. Here’s a classic example.

(* This fact function calls itself until it reaches the
   base case of fact 0. *)
let rec fact n =
  if n = 0 then 1
  else n * fact (n - 1)

let () =
  Printf.printf "%d\n" (fact 7);

  (* In OCaml, we can define recursive functions using
     the 'let rec' keyword. Here's a recursive fibonacci function *)
  let rec fib n =
    if n < 2 then n
    else fib (n - 1) + fib (n - 2)
  in

  Printf.printf "%d\n" (fib 7)

In OCaml, we use the let rec keyword to define recursive functions. The fact function demonstrates a simple recursive implementation of factorial calculation.

For the Fibonacci sequence, we define another recursive function fib. In OCaml, we don’t need to declare the function type explicitly before defining it, as the language has powerful type inference.

To run this program, save it as recursion.ml and use the OCaml compiler:

$ ocamlc -o recursion recursion.ml
$ ./recursion
5040
13

The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).

OCaml’s pattern matching and tail-call optimization make it particularly well-suited for recursive algorithms, often resulting in efficient and readable code.