Lists
7 min · OCaml
OCaml lists: built from head :: tail, accessed by pattern matching.
Enemy 1 of 5
List.hd and accessing elements
An OCaml list is either empty or a head joined to a tail with ::. Write elements with semicolons, not commas, and keep them all the same type.
This makes a list of three fruits and prints its first element using List.hd. Press Run to see it.
Why this works
An OCaml list is either empty (written `[]`) or built from a "head" element joined to a "tail" (the rest of the list) with the `::` operator, pronounced "cons." `[1; 2; 3]` is just convenient shorthand for `1 :: 2 :: 3 :: []`. Under the hood, every list is this same chain of cons cells terminating in the empty list. Notice OCaml lists use semicolons `;` between elements, not commas: commas in OCaml are reserved for tuples, a different data structure entirely, so mixing them up (`[1, 2, 3]`) is a very common early syntax error.
One important consequence of this structure: every element in an OCaml list must have the *same type*: a `int list` can't also hold a string. This is the type system enforcing consistency, and it's part of why OCaml programs that compile tend to have far fewer "wrong kind of value showed up here" bugs than in loosely-typed languages.
`List.hd` returns a list's first element (its head); the standard library groups this and other list functions under the `List` module, the same organizational pattern you saw with `String` functions. Calling `List.hd` on an empty list raises an exception, since there's no head to return, a case worth keeping in mind once you start writing your own list-processing functions.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.