It was my first time I saw a type definition like \'a. unit -> \'a
in Explicit polymorphic type in record
Q1: What i
'a.
means "for all types 'a". The OCaml top-level usually doesn't bother showing it, which is why it doesn't appear in the output. Any expression printed that contains type variables has an implicit forall at the start unless shown elsewhere.
When defining a function, it can be useful to add this at the start to ensure the type is polymorphic. e.g.
# let f : ('a -> 'a) = fun x -> x + 1;;
val f : int -> int =
Here, the 'a -> 'a
just constrains the function's output type to be the same as its input type, but OCaml is free to limit it further. With the 'a.
, this doesn't happen:
# let f : 'a. ('a -> 'a) = fun x -> x + 1;;
Error: This definition has type int -> int which is less general than
'a. 'a -> 'a
You need to specify the 'a.
when defining record or object types and you want to scope the type variable to an individual member rather than to the whole object.