Pragmatism, deliberately
OCaml's default is immutable data, and the first five lessons used nothing else. But OCaml was never a purist language. Some algorithms are naturally written with a mutable table (the sieve of Eratosthenes, dynamic programming, graph search with a visited set); some data is inherently a fixed-size block that is updated in place (an image, a matrix, a buffer of incoming bytes); and sometimes a counter in a loop is just the clearest way to say what you mean.
So OCaml gives you mutation, with two disciplines that keep it under control. Mutable things have their own types (int ref, a mutable field, 'a array, Hashtbl.t), so a reader can see where state may change. And the usual style is local mutation: a function may use a mutable array inside, but presents a pure interface to the world. The same pragmatism applies to errors: OCaml's exceptions are cheap and fast, and used well alongside the option and result types you already know.
Mutable things and exceptions
Definition— Reference
ref v creates a mutable cell holding v, of type 'a ref. !r reads it, r := v writes it, and incr r / decr r add or subtract one from an int ref. A reference is itself a record with one mutable field.
Definition— Mutable field
A record field declared mutable can be updated in place with r.field <- v. Every name bound to that record sees the change, because they all refer to the same record.
Definition— Array
[| 1; 2; 3 |] is an array: fixed length, elements of one type, read with a.(i) and written with a.(i) <- v in constant time. Out-of-range indexes raise Invalid_argument "index out of bounds".
Definition— Exception
exception E of t declares an exception that carries a t. raise (E v) interrupts evaluation until a matching handler is found: try e with E x -> handler, or a match e with ... | exception E x -> ... case. Exceptions are values of the extensible type exn.
State, structures and exceptions
References, loops, mutable fields, arrays
(* A record with a mutable field. *)
type account = { owner : string; mutable balance : int }
let () =
(* References: mutable cells. ! reads, := writes, incr adds one. *)
let count = ref 0 in
for i = 1 to 20 do
if i mod 3 = 0 then incr count
done;
Printf.printf "multiples of 3 up to 20: %d\n" !count;
let n = ref 27 and steps = ref 0 in
while !n <> 1 do
n := if !n mod 2 = 0 then !n / 2 else (3 * !n) + 1;
incr steps
done;
Printf.printf "27 reaches 1 after %d steps\n" !steps;
(* Mutable record fields are updated in place with <- *)
let acc = { owner = "Ines"; balance = 100 } in
acc.balance <- acc.balance + 50;
let same = acc in
same.balance <- same.balance - 30;
Printf.printf "%s has %d\n" acc.owner acc.balance;
(* Arrays: fixed length, constant-time access, mutable elements. *)
let squares = Array.init 6 (fun i -> i * i) in
squares.(0) <- -1;
Printf.printf "%s (length %d, sum %d)\n"
(String.concat " " (Array.to_list (Array.map string_of_int squares)))
(Array.length squares)
(Array.fold_left ( + ) 0 squares);
let scores = [| 72; 95; 61; 88 |] in
Array.sort compare scores;
Printf.printf "sorted: %s\n" (String.concat " " (List.map string_of_int (Array.to_list scores)))multiples of 3 up to 20: 6
27 reaches 1 after 111 steps
Ines has 120
-1 1 4 9 16 25 (length 6, sum 54)
sorted: 61 72 88 95The for loop counts upwards (for i = 20 downto 1 counts down); its body must be of type unit. The while loop is the Collatz process from lesson 2 again, now written imperatively; compare the two and decide which you find clearer. Both are idiomatic.
The account example shows the crucial difference between mutable and immutable data. let same = acc does not copy the record; it gives the same record a second name. Changing same.balance changes what acc.balance shows, which is why the result is 120 and not 150. With immutable records that question never arises, which is one reason OCaml makes immutability the default.
Arrays have most of the functions lists have (Array.map, Array.fold_left, Array.iter, Array.to_list), and some only an in-place structure can offer: Array.sort sorts the array itself and returns ().
Imperative algorithms, hash tables and buffers
(* The sieve of Eratosthenes: an algorithm that is naturally imperative. *)
let primes_up_to n =
let is_prime = Array.make (n + 1) true in
is_prime.(0) <- false;
is_prime.(1) <- false;
for i = 2 to n do
if is_prime.(i) then begin
let j = ref (i * i) in
while !j <= n do
is_prime.(!j) <- false;
j := !j + i
done
end
done;
List.filter (fun i -> is_prime.(i)) (List.init (n + 1) Fun.id)
let () =
print_endline (String.concat " " (List.map string_of_int (primes_up_to 50)));
(* Hashtbl: a mutable hash table. *)
let counts = Hashtbl.create 16 in
String.split_on_char ' ' "to be or not to be that is the question"
|> List.iter (fun w ->
let old = Option.value ~default:0 (Hashtbl.find_opt counts w) in
Hashtbl.replace counts w (old + 1));
(* Hashtbl order is unspecified, so sort before printing. *)
Hashtbl.fold (fun w c acc -> (w, c) :: acc) counts []
|> List.sort compare
|> List.iter (fun (w, c) -> Printf.printf "%s:%d " w c);
print_newline ();
(* Buffer: build a long string efficiently. *)
let buf = Buffer.create 64 in
for i = 1 to 5 do
Buffer.add_string buf (string_of_int i);
if i < 5 then Buffer.add_string buf " -> "
done;
print_endline (Buffer.contents buf)2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
be:2 is:1 not:1 or:1 question:1 that:1 the:1 to:2
1 -> 2 -> 3 -> 4 -> 5primes_up_to is a good example of local mutation. Inside, it allocates a boolean array and crosses out multiples in place; outside, it is a pure function from a number to a list. Callers cannot tell, and need not care, that the implementation is imperative. begin ... end is just a pair of parentheses with a nicer look, used around a multi-line imperative block.
Hashtbl is the standard mutable hash table: Hashtbl.replace sets a binding, Hashtbl.find_opt looks one up, and lookups and updates take constant time on average. Compare it with the immutable Map of the previous lesson: a Map keeps keys sorted, can be shared and kept in old versions safely, and costs logarithmic time per operation; a Hashtbl is usually faster but is mutated in place and iterates in an unspecified order. That last point is why the program sorts before printing; a test whose output depends on hash-table order is a test that will break one day.
Buffer accumulates text efficiently. Building a long string with repeated ^ copies everything each time; a buffer appends in amortised constant time.
Exceptions
type account = { owner : string; mutable balance : int }
(* An exception of our own, carrying data. *)
exception Insufficient_funds of { needed : int; available : int }
let withdraw acc amount =
if amount > acc.balance then
raise (Insufficient_funds { needed = amount; available = acc.balance });
acc.balance <- acc.balance - amount
(* A local exception to leave a loop early. *)
let first_negative arr =
let exception Found of int in
try
Array.iteri (fun i x -> if x < 0 then raise (Found i)) arr;
None
with Found i -> Some i
let () =
let acc = { owner = "Kwame"; balance = 80 } in
(try
withdraw acc 30;
withdraw acc 70;
print_endline "not reached"
with Insufficient_funds { needed; available } ->
Printf.printf "cannot take %d from %s, only %d left\n" needed acc.owner available);
(* Standard exceptions from the standard library. *)
(match int_of_string "12x" with
| n -> Printf.printf "parsed %d\n" n
| exception Failure msg -> Printf.printf "Failure: %s\n" msg);
(match List.assoc "z" [ ("a", 1) ] with
| v -> Printf.printf "found %d\n" v
| exception Not_found -> print_endline "Not_found");
(try ignore ([| 1; 2; 3 |].(5)) with Invalid_argument msg -> Printf.printf "Invalid_argument: %s\n" msg);
(try ignore (10 / (acc.balance - acc.balance)) with Division_by_zero -> print_endline "Division_by_zero");
(match first_negative [| 4; 8; -2; 7; -9 |] with
| Some i -> Printf.printf "first negative at index %d\n" i
| None -> print_endline "none");
(* Fun.protect runs ~finally whether or not the body raises. *)
match
Fun.protect
~finally:(fun () -> print_endline "closing the file")
(fun () ->
print_endline "reading the file";
failwith "disk error")
with
| () -> ()
| exception Failure msg -> Printf.printf "caught: %s\n" msgcannot take 70 from Kwame, only 50 left
Failure: int_of_string
Not_found
Invalid_argument: index out of bounds
Division_by_zero
first negative at index 2
reading the file
closing the file
caught: disk errorThe first withdrawal succeeds and the second raises Insufficient_funds, carrying the details as an inline record; the handler takes them apart with a pattern, just like a variant. The line after the failed withdrawal never runs.
match ... with exception handles exceptions and normal results in one place. It is often better than try, because the normal-result branch is outside the scope of the handler: an exception raised while processing the result will not be accidentally caught.
Four standard exceptions appear: Failure (raised by failwith and by functions such as int_of_string), Not_found (lookups), Invalid_argument (bad arguments, such as an index out of bounds) and Division_by_zero. Remember the _opt functions from lesson 3; they exist precisely so that ordinary "not found" situations need no exception at all.
first_negative uses a local exception, declared with let exception ... in, as a fast early exit from Array.iteri, which has no break. Raising and catching an exception in OCaml is very cheap, far cheaper than in Java or Python, so this is an accepted idiom. Finally, Fun.protect ~finally f runs f and then always runs the clean-up function, even when f raises, then lets the exception continue.
Under the hood: sharing, mutation and cheap exceptions
A mental model of memory explains most of this lesson's surprises.
Every name refers to a value; most values are pointers. An int, a char, a bool or a constant constructor fits in one machine word and is stored directly. A record, an array, a string, a list cell or a closure is a block on the heap, and a name bound to it holds a pointer. let same = acc copies the pointer, not the block. With immutable data this is invisible, because nobody can change the shared block; with a mutable field or an array it is exactly why both names see the change.
Immutable updates are cheaper than they look. { r with balance = 10 } allocates one new block and copies the fields, which are themselves small values or pointers; a new list cell or tree node is the same. OCaml's minor heap makes such allocations almost free, which is why idiomatic OCaml happily creates new values instead of mutating old ones.
Mutation is not free either. When a long-lived value is changed to point at a newly allocated one, the garbage collector must be told, through a small piece of code called a write barrier, so it does not miss the new value during its next minor collection. In tight numeric loops this rarely matters; it is one reason why "mutable means faster" is not automatically true in OCaml. Arrays of floats, and records whose fields are all floats, are stored unboxed (the numbers sit directly in the block), so numeric code on float array is compact and fast.
Raising an exception is a jump. When you enter a try, the runtime records where the handler is; raise unwinds directly to the most recent matching handler without inspecting each stack frame on the way, and the exception value itself is just a small block. That is why OCaml programmers use local exceptions for early exits without a second thought, while the same pattern in languages whose exceptions capture stack traces by default would be slow. (When you want a backtrace for debugging, set the environment variable OCAMLRUNPARAM=b or call Printexc.record_backtrace true.)
Choosing between exceptions, option and result
The OCaml community's working consensus, reflected in the official documentation and in most modern libraries:
| Situation | Use | Why |
|---|---|---|
| A value may simply be absent (lookup, search, parse) | option | The caller is expected to handle absence; the type says so. |
| An operation may fail in ways the caller should handle (validation, I/O errors, a parse with a message) | result with a descriptive error type | The failure is part of the function's contract, visible in its type, and cannot be forgotten. |
| A bug or a broken invariant (index out of range, "this case cannot happen") | an exception, usually Invalid_argument or assert false | No caller can sensibly recover; the program should stop loudly. |
| Leaving a deep computation early, inside one module | a local exception | Fast and contained; it never escapes the function. |
| Errors from the operating system (files, sockets) | exceptions such as Sys_error, often converted to result at a boundary | That is what the standard library raises; wrap it where the rest of your code expects results. |
The functions that raise exceptions are usually named plainly (List.find, Hashtbl.find, int_of_string), with an _opt companion that returns an option. In application code, reach for the _opt version unless you are certain the value is there.
On mutation, the rule of thumb is just as practical: use immutable data by default, because sharing it is always safe (including across threads, as lesson 8 shows); use mutable structures locally, inside a function or behind a module's abstract type, when they make an algorithm simpler or faster; and keep global mutable state to a minimum.
Common misconceptions
Misconception
"let x = ref 0 makes x a mutable variable." x is still an immutable name; it is bound to a mutable cell. That is why you must write !x to read the contents and x := 5 to change them. Forgetting the !, as in x + 1, gives the error "The value x has type int ref but an expression was expected of type int": the compiler reminding you of the difference.
Misconception
"let b = a copies the array (or the mutable record)." It gives the same array a second name. To copy, use Array.copy a, or build a new record with { r with ... }.
Misconception
"I can break out of a for loop, or return from the middle of a function." OCaml has neither break, continue nor return. A loop runs to its end; a function's value is the value of its body. To stop early, write the loop as a recursive function that simply does not recurse, use a while loop with a flag, or raise a local exception as first_negative does. Many loops that need break in other languages are better expressed with List.find_opt, Array.exists or Seq.take_while.
Misconception
"Exceptions are slow, so avoid them." In OCaml, raising and handling an exception costs little more than a function return; using one to break out of a loop is idiomatic. The reasons to prefer option and result are clarity and type-checked handling, not speed.
Misconception
"Array.make 3 (Array.make 3 0) creates a 3 × 3 grid." It creates one inner array and puts it in all three slots, so changing grid.(0).(0) changes every row. Use Array.make_matrix 3 3 0 or Array.init 3 (fun _ -> Array.make 3 0).
Exercises
1. Mutability, arrays and exceptions
CoreComputationalWhat does this program print?
let () =
let a = [| 1; 2; 3 |] in
let b = a in
let c = Array.copy a in
b.(0) <- 10;
c.(1) <- 20;
Printf.printf "%d\n" (a.(0) + a.(1) + a.(2))
2. Mutability, arrays and exceptions
Warm-upComputationalWhat does this program print?
let () =
let total = ref 0 in
for i = 1 to 4 do
total := !total + (i * i)
done;
let r = ref 1 in
while !r < 100 do
r := !r * 3
done;
Printf.printf "%d %d\n" !total !r
3. Mutability, arrays and exceptions
CoreComputationalWhat does this program print?
exception Too_big of int
let check n = if n > 10 then raise (Too_big n) else n
let () =
let result =
try
let a = check 4 in
let b = check 12 in
let c = check 30 in
a + b + c
with Too_big n -> -n
in
Printf.printf "%d\n" result
4. Mutability, arrays and exceptions
CoreHumanYou are writing parse_config : string -> ... for a file format. Callers should be told what was wrong (a missing key, a bad number) and must handle it. Which return type fits best?
5. Mutability, arrays and exceptions
StretchComputationalWhat does this program print?
let () =
let g = Array.make 2 (Array.make 2 0) in
g.(0).(1) <- 5;
Printf.printf "%d\n" g.(1).(1)
6. Mutability, arrays and exceptions
CoreComputationalWhat does this program print?
let () =
(try
Fun.protect
~finally:(fun () -> print_string "C ")
(fun () ->
print_string "A ";
ignore (List.assoc 1 []);
print_string "B ")
with Not_found -> print_string "D ");
print_newline ()
7. Mutability, arrays and exceptions
CoreHumanAn undo feature must keep every previous version of a table of settings, and the settings are shown sorted by name. Which structure fits best?
Further reading and resources
- The Array module
- The Hashtbl moduleMutable hash tables, and the Hashtbl.Make functor for custom keys.
- The Buffer module
- Error handling (OCaml documentation)The official comparison of exceptions, option and result, with recommendations.
- The OCaml Manual: The core language, imperative features