OCaml enumerated types
In OCaml, enumerated types, also known as variant types, provide a way to define a set of distinct values that a variable can take on. Each value in an enumerated type is called a variant or a constructor. They are defined using the type keyword followed by the name of the type, an equal sign, and a set of variant constructors separated by the vertical bar |.
Here’s an example of an enumerated type called color with three variants:
type color = Red | Green | Blue
In this example, color is the name of the enumerated type, and Red, Green, and Blue are the variants of the type. Once you have defined an enumerated type, you can create variables of that type and assign them one of the variants.
let my_color : color = Red
You can also use pattern matching to match against the variants of an enumerated type and perform different actions depending on the variant.
let color_to_string (c:color) =
match c with
| Red -> "red"
| Green -> "green"
| Blue -> "blue"
In this example, the function color_to_string takes a variable c of type color and uses pattern matching to match c against the variants of the color type. Depending on the variant, the function returns the corresponding string representation.
It’s worth noting that Enumerated types are very useful when you want to represent a set of distinct values in your code, they also help the code to be more readable, and in some cases can also help to detect errors.
Here is another example:
type rps = Rock | Paper | Scissors
type outcome = Win | Draw | Loss
let play (p1 : rps) (p2 : rps) : outcome =
match (p1, p2) with
| (Rock, Scissors) -> Win
| (Paper, Rock) -> Win
| (Scissors, Paper) -> Win
| _ when p1 = p2 -> Draw
| _ -> Loss
Calling play will return the outcome (from the perspective of player 1) of the game of rock-paper-scissors.