Skip to content
Part IA Michaelmas Term

Arrays and Mutable Lists

OCaml arrays

OCaml arrays are like references that hold multiple elements instead of one. An n-element array’s elements are designated by indices 0 to n−1.

Core array operations

OperationTypeDescription
Array.make n xint -> 'a -> 'a arrayCreate array of size n, all cells = x
Array.init n fint -> (int -> 'a) -> 'a arrayCreate array with cell i = f(i)
Array.get a i'a array -> int -> 'aReturn a[i]
Array.set a i x'a array -> int -> 'a -> unitSet a[i] := x

Examples

let aa = Array.init 5 (fun i -> i * 10)
(* [|0; 10; 20; 30; 40|] *)

Array.get aa 3      (* => 30 *)
Array.set aa 3 42   (* aa[3] := 42, returns () *)

Bounds checking

OCaml arrays are bounds-checked. Accessing Array.get ar 20 on a 20-element array raises Invalid_argument "index out of bounds". This is much safer than C, where an array is merely a starting address with no size information, making buffer overrun attacks possible.

Two-dimensional arrays

An n × n identity matrix can be created as an array of arrays:

Higher dimensions are represented similarly by nesting. OCaml arrays cannot grow: if you outgrow an array, you must allocate a new one (typically double the size) and copy the data.

Mutable lists

type 'a mlist =
  | Nil
  | Cons of 'a * 'a mlist ref

A mutable list is like an ordinary list, but the tail pointer is a reference rather than a direct value. This allows in-place modification: you can redirect the tail of a cons cell to point to a different list.

This is analogous to linked data structures taught in algorithms courses, where nodes contain pointers to other nodes. The syntax differs from C/Java, but the principles are the same.

Comparison of list types

TypeTailMutation
'a list (built-in)Direct 'a listImmutable
'a seq (lazy)unit -> 'a seq (thunk)Not directly; lazily computed
'a mlist (mutable)'a mlist refIn-place via :=

A tripos question might ask you to code odds (return alternate elements) for all three list types, or to detect cycles in a mutable list using reference equality (==).