OCaml “lists” are inductively defined linked lists. A list is either empty ([]
) or an element followed by a list (elem::list
).
You can think of the linked list definition as
type 'a list =
| []
| (::) of 'a * 'a list
To process a list, you have to use pattern matching and usually recursion as well:
match list with
| [] -> (* handle empty case *)
| x::xs -> (* handle non-empty case *)
Here, x
is a newly defined variable bound to the element and xs
is a new variable set to the “tail” of the list.
You cannot have O(1) indexing of linked lists. You must linearly traverse them. However, OCaml does have arrays, which are fixed-size containers with O(1) indexing. Arrays are written [|1; 2; 3|]
and accessed with array.(index)
.