14 Lists

Lists in OCaml are written in square brackets.

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.

This is the int list containing the element 1. We separate elements in a list with a ;.

Lists can have any type. Here's a list of floats:

And here's a list of lists of ints.

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

We can even write an entire list like this

(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.