3.6. Type Synonyms#
A type synonym is a new name for an already existing type. For example, here are some type synonyms that might be useful in representing some types from linear algebra:
type point = float * float type vector = float list type matrix = float list list
type point = float * float
type vector = float list
type matrix = float list list
Anywhere that a
float * float is expected, you could use
vice-versa. The two are completely exchangeable for one another. In the
get_x doesn’t care whether you pass it a value that is
annotated as one vs. the other:
let get_x = fun (x, _) -> x let p1 : point = (1., 2.) let p2 : float * float = (1., 3.) let a = get_x p1 let b = get_x p2
val get_x : 'a * 'b -> 'a = <fun>
val p1 : point = (1., 2.)
val p2 : float * float = (1., 3.)
val a : float = 1.
val b : float = 1.
Type synonyms are useful because they let us give descriptive names to complex types. They are a way of making code more self-documenting.