Lists in OCaml are written in square brackets.
[];;
- : 'a list = []
This is the empty list. It has elements of type 'a, because there's nothing in it. Since there's noting in it, it doesn't have to have a type.
[1];;
- : int list = [1]
This is the int list containing the element 1. We separate elements in a list with a ;.
[1110; 2110; 3110];;
- : int list = [1110; 2110; 3110]
Lists can have any type. Here's a list of floats:
[0.5; 1.0; 1.5; 2.0];;
- : float list = [0.5; 1.; 1.5; 2.]
And here's a list of lists of ints.
[[1; 2]; [3; 4]; [5; 6]];;
- : int list list = [[1; 2]; [3; 4]; [5; 6]]
Note that this is an int list list, you can read this backwards, it's a list of lists of ints.
There's another syntax for writing lists. :: appends elements together, for example
1 :: [2; 3];;
- : int list = [1; 2; 3]
We can even write an entire list like this
1 :: 2 :: 3 :: [];;
- : int list = [1; 2; 3]
(Note we need the [], because we're appending to the empty list)
Lists in OCaml are immutable. This means that we can't change elements. They are also singly-linked, because they happen to work very nicely. Note that they won't always work perfectly, and you might need something else. They're good if you need to use short-to-medium length lists (up to about 10k elements). Next week, we'll go over the implementation of lists in OCaml.