OCaml Lists
A list is an immutable, ordered sequence of values of the same type. Lists are the workhorse data structure of functional OCaml. They are written with square brackets and semicolons:
let primes = [ 2; 3; 5; 7; 11 ]
let names = [ "Ada"; "Alan"; "Grace" ]
let empty = []
let () =
Printf.printf "%d %d %d\n" (List.length primes) (List.length names) (List.length empty);
Printf.printf "first prime: %d\n" (List.hd primes);
print_endline (String.concat ", " names)5 3 0
first prime: 2
Ada, Alan, Grace
The types are int list and string list. The empty list [] has type 'a list: it can become a list of anything.
Warning:
[1, 2, 3]with commas is not a three-element list. It is a one-element list containing the tuple(1, 2, 3), of type(int * int * int) list. Always separate list elements with;.
How lists are built
A list is either:
- the empty list
[], or - an element (the head) followed by another list (the tail), written
head :: tail.
:: is pronounced "cons". The literal [1; 2; 3] is just a nicer way of writing 1 :: (2 :: (3 :: [])).
let print_list lst = print_endline ("[" ^ String.concat "; " (List.map string_of_int lst) ^ "]")
let () =
let tail = [ 2; 3 ] in
let whole = 1 :: tail in
print_list whole;
print_list (1 :: 2 :: 3 :: []);
print_list (0 :: whole);
print_list tail (* unchanged: lists are immutable *)[1; 2; 3]
[1; 2; 3]
[0; 1; 2; 3]
[2; 3]
Adding to the front with :: is instant (it allocates one cell and shares the rest). whole and 0 :: whole share the same cells in memory, which is safe because nothing can modify them.
Lists are singly linked
| Operation | Cost |
|---|---|
x :: lst (add to front) |
O(1) |
List.hd, List.tl |
O(1) |
List.length lst |
O(n) |
List.nth lst i (index access) |
O(i) |
a @ b (append) |
O(length of a) |
List.rev lst |
O(n) |
If you need fast random access by index, use an array instead.
Concatenation and other basics
let show lst = String.concat " " (List.map string_of_int lst)
let () =
let a = [ 1; 2; 3 ] and b = [ 10; 20 ] in
print_endline (show (a @ b));
print_endline (show (List.rev a));
Printf.printf "%d\n" (List.nth b 1);
Printf.printf "%b %b\n" (List.mem 20 b) (List.mem 4 a);
print_endline (show (List.init 5 (fun i -> i * i)));
print_endline (show (List.concat [ [ 1 ]; [ 2; 3 ]; []; [ 4 ] ]))1 2 3 10 20
3 2 1
20
true false
0 1 4 9 16
1 2 3 4
List.hd [] and List.nth lst 99 raise exceptions (Failure "hd", Failure "nth"). The safe way to read a list is pattern matching, coming next.
Lists of lists
Elements can be any type, including other lists or tuples:
let () =
let grid = [ [ 1; 2; 3 ]; [ 4; 5; 6 ] ] in
List.iter
(fun row -> print_endline (String.concat " " (List.map string_of_int row)))
grid;
let pairs = [ ("apples", 3); ("pears", 5) ] in
List.iter (fun (fruit, n) -> Printf.printf "%s: %d\n" fruit n) pairs1 2 3
4 5 6
apples: 3
pears: 5
A first look at matching on lists
let describe lst =
match lst with
| [] -> "empty"
| [ x ] -> "just " ^ string_of_int x
| x :: _ -> "starts with " ^ string_of_int x
let () =
print_endline (describe []);
print_endline (describe [ 42 ]);
print_endline (describe [ 7; 8; 9 ])empty
just 42
starts with 7
Test yourself
What is the type of [1, 2, 3] (with commas)?
int list(int * int * int) listint array- A syntax error
What does 0 :: [1; 2] produce?
[1; 2; 0][0; 1; 2][[0]; 1; 2]- A type error
Which operation on a list is O(1)?
List.lengthList.nth lst 5x :: lsta @ b