Benefits of OCaml
Variant types
The OCaml type system supports two types used to represent values of one of several possibilities. These are known as variants and polymorphic variants.
For example, the following variant defines a type that is one of two possibilities, either On or Off:
# type button = On | Off;;
type button = On | Off
# On;;
- : button = On
# Off;;
- : button = Off
Variant types can be recursive (refer to themselves) and variant type constructors can carry data. For example, tree may be represented as:
# type tree = Node of tree list;;
type tree = Node of tree list
# Node [];;
- : tree = Node []
# Node [Node []; Node [Node []]; Node []];;
- : tree = Node [Node []; Node [Node []]; Node []]
Variant types provide an elegant way to represent a wide variety of data structures. Moreover, pattern matching allows variant types to be manipulated very efficiently and robustly.
|
Read OCaml for Scientists now!
|
|