??
Last Element of a List
File: list_last_elem.ml
Overview
Find the last element of a list safely using Option types — no exceptions, no crashes on empty lists. This is a classic OCaml exercise that demonstrates safe programming through the type system.
The Code
Three patterns match every possible list shape:
let rec last = function
| [] -> None (* empty list — nothing to return *)
| [x] -> Some x (* single element — that's the last one *)
| _ :: t -> last t (* multiple elements — recurse on the tail *)
Why Option Types Matter
Unlike languages that return null or throw exceptions, OCaml forces you to handle the empty case. The compiler won't let you forget. This is one of OCaml's strongest safety guarantees.
Output
last [1; 2; 3] = Some 3 last [42] = Some 42 last [] = None