(Introduced in OCaml 3.12, short syntax added in 4.03)
The expression fun ( type typeconstr-name ) -> expr introduces a type constructor named typeconstr-name which is considered abstract in the scope of the sub-expression, but then replaced by a fresh type variable. Note that contrary to what the syntax could suggest, the expression fun ( type typeconstr-name ) -> expr itself does not suspend the evaluation of expr as a regular abstraction would. The syntax has been chosen to fit nicely in the context of function declarations, where it is generally used. It is possible to freely mix regular function parameters with pseudo type parameters, as in:
and even use the alternative syntax for declaring functions:
If several locally abstract types need to be introduced, it is possible to use the syntax fun ( type typeconstr-name1 … typeconstr-namen ) -> expr as syntactic sugar for fun ( type typeconstr-name1 ) -> … -> fun ( type typeconstr-namen ) -> expr. For instance,
This construction is useful because the type constructors it introduces can be used in places where a type variable is not allowed. For instance, one can use it to define an exception in a local module within a polymorphic function.
Here is another example:
(Introduced in OCaml 4.00)
The (type typeconstr-name) syntax construction by itself does not make polymorphic the type variable it introduces, but it can be combined with explicit polymorphic annotations where needed. The above rule is provided as syntactic sugar to make this easier:
is automatically expanded into
This syntax can be very useful when defining recursive functions involving GADTs, see the section 8.10 for a more detailed explanation.
The same feature is provided for method definitions.