OCaml tuples and type synonyms
In OCaml, tuples are a way to group a fixed number of elements of different types together. Here’s an example of a tuple with two elements, a string and an int:
let person_tuple = ("Bob", 140)
You can also extract the elements of a tuple using pattern matching:
let (name, height) = person_tuple in
print_string name;
print_int height
In order to make the code more readable, you can use type synonyms to give more descriptive names to the types of the elements in the tuple.
type height = int
type name = string
type person = name * height
let person_tuple : person = ("Bob", 140)
With this definition, you can use person as the type for person_tuple and it becomes more clear what kind of elements the tuple is holding. name and height are type synonyms for string and int respectively, making the code more readable and less verbose.
Read other posts