Variants are user-defined types that can take on several different labeled forms.
Basic Variant Type
type color =
| Red
| Green
| Blue
Pattern match to convert a color to a string:
let to_string color =
match color with
| Red -> "red"
| Green -> "green"
| Blue -> "blue"
Variants with Data
Constructors can also hold values:
type card_value =
| Ace
| King
| Queen
| Jack
| Number of int
let one_card_value : card_value = Queen
let another_card_value : card_value = Number 8
Convert a card to a string:
let card_value_to_string card_value =
match card_value with
| Ace -> "Ace"
| King -> "King"
| Queen -> "Queen"
| Jack -> "Jack"
| Number i -> Int.to_string i
Your Turn
Write a function to assign a score to a card: Aces = 11, Face cards = 10, Numbers = value
let card_value_to_score card_value =
failwith "For you to implement"