OCaml References and Mutable Fields
OCaml encourages immutable data, but it is not a "pure" language. When mutation is the clearest solution, such as a counter, a cache, or a performance-critical loop, you can use references and mutable record fields.
References
A reference is a mutable box holding one value. Create it with ref, read it with !, and update it with :=:
let () =
let count = ref 0 in
Printf.printf "start: %d\n" !count;
count := !count + 1;
count := !count + 10;
incr count; (* shorthand for count := !count + 1 *)
Printf.printf "now: %d\n" !count;
let name = ref "draft" in
name := !name ^ "-final";
print_endline !namestart: 0
now: 12
draft-final
The type of count is int ref. ! is not boolean "not" (that is not); it means "dereference".
| Operation | Syntax | Type |
|---|---|---|
| create | ref v |
'a -> 'a ref |
| read | !r |
'a ref -> 'a |
| write | r := v |
'a ref -> 'a -> unit |
| add/subtract 1 | incr r, decr r |
int ref -> unit |
Shadowing versus mutation
A let binding can never change, but the contents of a reference can. Closures that capture a reference see the updates:
let make_counter () =
let n = ref 0 in
fun () ->
incr n;
!n
let () =
let next_id = make_counter () in
let other = make_counter () in
let a = next_id () in
let b = next_id () in
let c = next_id () in
Printf.printf "%d %d %d | %d\n" a b c (other ())1 2 3 | 1
Each counter has its own private reference, hidden inside the closure. This is a common way to keep state without global variables.
Note: We bound
a,b,cwith separatelets on purpose. OCaml does not specify the evaluation order of function arguments (in practice it is often right to left), soPrintf.printf "%d %d" (next_id ()) (next_id ())might print2 1.
Mutable record fields
Mark a field mutable to update it in place with <-:
type player = { name : string; mutable score : int; mutable lives : int }
let hit p =
p.lives <- p.lives - 1;
if p.lives = 0 then Printf.printf "%s is out!\n" p.name
let () =
let p = { name = "Zed"; score = 0; lives = 2 } in
p.score <- p.score + 150;
hit p;
Printf.printf "%s: score %d, lives %d\n" p.name p.score p.lives;
hit pZed: score 150, lives 1
Zed is out!
A reference is in fact just a record with one mutable field: type 'a ref = { mutable contents : 'a }.
Aliasing
With mutable data, two names can refer to the same value. A change through one name is visible through the other:
type box = { mutable items : string list }
let () =
let a = { items = [ "pen" ] } in
let b = a in (* same box, not a copy *)
let c = { items = a.items } in (* a new box *)
b.items <- "ink" :: b.items;
Printf.printf "a: %s\n" (String.concat "," a.items);
Printf.printf "c: %s\n" (String.concat "," c.items);
Printf.printf "a == b: %b, a == c: %b\n" (a == b) (a == c)a: ink,pen
c: pen
a == b: true, a == c: false
== (physical equality) tells you whether two names point at the same mutable value.
When to use mutation
Mutation is fine when it is local: a function that uses a reference internally but still behaves like a pure function from the outside.
let sum_of_squares n =
let total = ref 0 in
for i = 1 to n do
total := !total + (i * i)
done;
!total
let () = Printf.printf "%d %d\n" (sum_of_squares 10) (sum_of_squares 100)385 338350
Callers of sum_of_squares cannot tell that it uses a reference. Shared global mutable state, on the other hand, makes code harder to test and is unsafe with parallel domains (see the domains lesson, which uses Atomic instead).
Test yourself
Given let r = ref 5, how do you read its value?
r!rr.value*r
How do you update the mutable field count of record t to 3?
t.count := 3t.count <- 3t.count = 3{ t with count = 3 }
After let a = ref 1 in let b = a in b := 2, what is !a?
- 1
- 2
- An error
- It depends on evaluation order