Variants are a new way to build data types.
Perhaps you've seen a type that allows you to enumerate through constants, like an enum.
You can do something similar with variants.
type primary_color = Red | Green | Blue
type primary_color = Red | Green | Blue
let r = Red
val r : primary_color = Red
See, we have a type primary_color now!
Let's make a variant for shapes!
type point = float * float
type shape =
(* lets represent a circle by it's center and it's radius*)
(* we can use the "of" keyword to make it carry more data*)
| Circle of {center: point; radius: float}
(* let's represent rectangles with their lower left
coordinate and their upper right coordiante.*)
| Rectangle of {lower_left: point; upper_right: point}
type point = float * float
type shape =
Circle of { center : point; radius : float; }
| Rectangle of { lower_left : point; upper_right : point; }
Now let's make a rectangle and a circle!
let c1 = Circle {center = (0., 0.); radius = 1.}
val c1 : shape = Circle {center = (0., 0.); radius = 1.}
let r1 = Rectangle {lower_left = (-1., -1.); upper_right = (1., 1.)}
val r1 : shape = Rectangle {lower_left = (-1., -1.); upper_right = (1., 1.)}
These variables now carry all the data we need to represent our points!