Polymorphism shows up in OCaml in many places. The polymorphic types discussed on that wiki are simply parameterized types. In some sense, they are type-level functions. To define a one-parameter type:
type 'a <name> = <definition using 'a>
For example
type 'a tagged = { value: 'a; tag: int }
In the <definition>
part you use the type name ('a
) as a formal parameter standing for whatever concrete type is supplied later.
After declaring the type (which declares value
and tag
as record fields), you can make values of the type:
# { value = "abc"; tag = 4 };;
- : string tagged = {value = "abc"; tag = 4}
The compiler infers that the type of this value is string tagged
because the value
field has type string
.
Multiple parameter types are defined using parentheses to enclose the type parameters:
type ('a, 'b) name = <definition using 'a and 'b>
For example:
type ('a, 'b) paired = { first: 'a; second: 'b }
This defines the field names first
and second
, which you can then use to make values:
# { first = 1.5; second = [3] };;
- : (float, int list) paired = {first = 1.5; second = [3]}
To summarize, the syntax for making polymorphic (parameterized) types is the same as the syntax for making types, extended with the use of symbols like 'a
for the type parameters.