OCaml By Examples

variants

utop

Variants are what is known as an `enum` in other languages, although variants are much more powerful in OCaml: they can hold data of different types.
utop # type container = 
| SmallBox
| BigBox of int
| HugeBox of int * string;;
type container = SmallBox | BigBox of int | HugeBox of int * string

utop # let box = BigBox(5);;
val box : container = BigBox 5
To use a variant, use a `match` statement.
utop # match box with
| BigBox (i) -> printf "a big box of %d\n" i
| _ -> print_endline "something else";;
a big box of 5
- : unit = ()
next: lists