Closures in OCaml

OCaml supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

let int_seq () =
  let i = ref 0 in
  fun () ->
    i := !i + 1;
    !i

let () =
  (* We call int_seq, assigning the result (a function)
     to next_int. This function value captures its
     own i value, which will be updated each time
     we call next_int. *)
  let next_int = int_seq () in

  (* See the effect of the closure by calling next_int
     a few times. *)
  Printf.printf "%d\n" (next_int ());
  Printf.printf "%d\n" (next_int ());
  Printf.printf "%d\n" (next_int ());

  (* To confirm that the state is unique to that
     particular function, create and test a new one. *)
  let new_ints = int_seq () in
  Printf.printf "%d\n" (new_ints ())

This function int_seq returns another function, which we define anonymously in the body of int_seq. The returned function closes over the variable i to form a closure.

In OCaml, we use a reference (ref) to create a mutable variable i. The inner function updates this reference and returns its value.

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

$ ocamlc -o closures closures.ml
$ ./closures
1
2
3
1

The last feature of functions we’ll look at for now is recursion.