Examples of Variants
Explore how to define and use variants in ReasonML by creating shape variants and tennis player states. Understand how constructors and pattern matching work to handle different data types and states within your programs.
We'll cover the following...
The shape Variant
We’ll create a shape variant which contains the Square, Circle, and Triangle constructors. Each constructor will have arguments of the float type as its dimensions.
Whenever one of the constructors is called, the area for that shape will be calculated through the getArea() method.
Implementation
Tennis Players
In this example, we have created two variants, player and turn. The tennis match has two players, and each player can either serve or receive based on the turn variant.
For this purpose, turn will use the player variant in its constructors. This is an example of variants using other variants as data types.
The rest is just pattern matching through switch expressions:
In the next lesson, we’ll explore the built-in optional variant data type.