Variant

References: CS3110 - Variants CS3110 - Algebraic Data Types ocaml.org - Generalized Algebraic Data Types

Variants

 1type invertebrate =
 2| Insects
 3| Arachnid
 4| Mollusk
 5| Worm;;
 6
 7type vertebrate = 
 8| Bird
 9| Fish
10| Amphibian
11| Mammal
12| Reptile;;
13
14type animal =
15| Invertebrate of invertebrate
16| Vertebrate of vertebrate;;
17
18let hawk = Vertebrate Bird;;
19let ant = Insect;;
20
21let get_animal_category a = 
22  match a with
23  | Vertebrate _ -> "vertebrate"
24  | Invertebrate _ -> "invertebrate"
25;;
1get_animal_category hawk;;
- : string = "vertebrate"
1get_animal_category ant;;
Error: This expression has type invertebrates
       but an expression was expected of type animals

Algebaric Data Types

1type string_or_int = 
2| String of string
3| Int of int;;
4
5let a = String "apple";;
val a : string_or_int = String "apple"