Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 40 ยท Imperative Features and Exceptions

References, Mutable Fields and Loops: Imperative OCaml

OCaml is functional first, but it has first-class imperative features. Learn refs, mutable record fields, arrays, for and while loops, sequencing and when mutation is the right tool.

OCaml is often called a functional language, but it is really a multi-paradigm one. Values are immutable by default, and you opt in to mutation where it helps: counters, caches, in-place array algorithms, graph traversals, performance-critical loops. Mutation is explicit in the types and in the syntax, which makes it easy to see where state lives.

OCaml is not available in the site's code runners, so the ocaml blocks are read-only and printed results appear only where they are certain. The Python stand-ins mirror the same programs.

References

A reference is a box holding a value that can change. Create one with ref, read it with !, change it with :=:

OCAML
let counter = ref 0

let () =
  counter := !counter + 1;
  counter := !counter + 1;
  Printf.printf "%d\n" !counter
(* prints: 2 *)

The type is int ref. ! is a prefix dereference, not "not". Boolean negation is not. Standard helpers: incr counter, decr counter.

A reference is just a record with one mutable field, defined in the standard library as:

OCAML
type 'a ref = { mutable contents : 'a }

So !r is r.contents and r := v is r.contents <- v.

A closure with private state

References are captured by closures, which gives you a tidy private counter:

OCAML
let make_counter () =
  let n = ref 0 in
  fun () ->
    incr n;
    !n

let next = make_counter ()
let () = Printf.printf "%d %d %d\n" (next ()) (next ()) (next ())
(* prints: 1 2 3 *)

Every call to make_counter () creates a fresh n, so independent counters do not interfere.

Mutable record fields

Mark individual record fields mutable and assign them with <-:

OCAML
type account = { id : string; mutable balance : int }

let deposit acct amount = acct.balance <- acct.balance + amount

let () =
  let a = { id = "A1"; balance = 100 } in
  deposit a 50;
  Printf.printf "%s: %d\n" a.id a.balance
(* prints: A1: 150 *)

Only fields marked mutable can be assigned; id is fixed. This lets you protect identity while permitting state changes.

Arrays

Arrays are mutable, fixed-size and O(1) indexed:

OCAML
let a = Array.make 5 0              (* [|0; 0; 0; 0; 0|] *)
let () = a.(2) <- 7                 (* assignment uses .( ) and <- *)
let b = Array.init 5 (fun i -> i * i)   (* [|0; 1; 4; 9; 16|] *)
let n = Array.length b              (* 5 *)

Out-of-bounds access raises Invalid_argument "index out of bounds". More on arrays in the earlier chapter on lists, arrays and records; the key point here is that array elements are mutated in place.

Array.make 3 (ref 0) creates one reference shared by all three slots. For separate copies use Array.init 3 (fun _ -> ref 0). The same trap applies to Array.make n [||]-style nested arrays: Array.make_matrix builds proper rows.

Sequencing and unit

The semicolon ; evaluates its left side, discards the result, and continues. The left side should have type unit:

OCAML
let () =
  print_string "a";
  print_string "b";
  print_newline ()
(* prints: ab *)

unit has the single value (). A function that exists only for its effect returns unit. An if without else must have type unit, since the missing branch returns ():

OCAML
if !counter > 3 then print_endline "big"

for and while loops

OCAML
let () =
  for i = 1 to 3 do
    Printf.printf "%d " i
  done;
  print_newline ()
(* prints: 1 2 3 *)

let () =
  for i = 3 downto 1 do
    Printf.printf "%d " i
  done
(* prints: 3 2 1 *)

let sum_to n =
  let total = ref 0 in
  let i = ref 1 in
  while !i <= n do
    total := !total + !i;
    incr i
  done;
  !total
(* sum_to 100 = 5050 *)

for counts inclusively and its variable is immutable inside the body. There is no break or continue. To stop early either use a recursive function, a while loop with a flag, or a local exception (see exceptions).

In-place array algorithm

Bubble sort, a classic imperative example:

OCAML
let bubble_sort a =
  let n = Array.length a in
  for i = 0 to n - 2 do
    for j = 0 to n - 2 - i do
      if a.(j) > a.(j + 1) then begin
        let tmp = a.(j) in
        a.(j) <- a.(j + 1);
        a.(j + 1) <- tmp
      end
    done
  done

begin ... end is the same as parentheses, used to group a sequence in an if branch.

Stand-in: the same state in Python

Python Stand-in: closures, mutable records and loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When to use mutation

Mutation is a good fit for:

  • counters and accumulators inside one function (kept local, invisible outside),
  • caches and memo tables,
  • algorithms that are naturally in place (sorting, dynamic programming tables, union-find),
  • performance-sensitive code that avoids allocation.

Prefer immutable data and fold for most logic. The functional version is usually shorter and has no hidden state, which helps testing and concurrency. A good habit is to confine a ref to one function. If the mutation does not escape, the function still looks pure from outside.

OCaml 5 programs can run on several cores, so shared mutable state needs care: use Atomic or Mutex, covered in the libraries lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does !r do when r is int ref?

    ! is the dereference operator; boolean negation is not.
  2. 2. Which line updates a mutable record field?

    <- assigns a mutable field or array element; := assigns a ref.
  3. 3. What does Array.make 3 (ref 0) produce?

    The value argument is evaluated once and the same reference is placed in every slot.
  4. 4. How do you exit a for loop early in OCaml?

    OCaml has no break or continue statements.

Summary

  • ref, !, :=, incr and decr give you mutable variables. A ref is a record with one mutable field.
  • mutable record fields change with <- and arrays with a.(i) <- v.
  • for and while loops are available but have no break. ; sequences unit-typed expressions.
  • Use mutation locally where it simplifies code and keep the rest immutable.

Next: Exceptions