Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
42 lines (26 sloc) 1.36 KB
<h3>Explicit Polymorphic Type Annotations</h3>
<p>OCaml 3.12 introduces a new syntax to require that a type be
<p>Let's start with what was there before. Many people thought that
they could already force a polymorphic type on a function:<p>
<p><code>let f : 'a -> 'a = function x -> x + 1</code></p>
<br />
<p>Although you might have thought you were forcing a polymorphic type
on the function, you were only enforcing a constraint of equality
between the argument type and the result type.</p>
<p>With explicit polymorphism, you can force the polymorphism (and get
an error, of course):<p>
<p><code>let f : 'a.'a -> 'a = function x -> x + 1</code></p>
<br />
<p>This notation can also be used to define really polymorphic
recursive methods. </p>
<p>Let's define a new tree type:</p>
<p><code>type 'a t = Leaf of 'a | Node of ('a * 'a) t</code></p>
<br />
<p>If we try to compute the depth of that tree, OCaml will complain: <p>
<p><code>let rec depth = function Leaf _ -> 1 | Node x -> 1 + depth x</code></p>
<br />
<p>Indeed, depth is a recursive function, and the typer does not allow
to use it will two different types of arguments. But now, with
explicit polymorphism, you can tell the typer that it's ok to do so, since the function is polymorphic:</p>
<p><code>let rec depth : 'a. 'a t -> _ = function Leaf _ -> 1 | Node x -> 1 + depth x</code></p>
Something went wrong with that request. Please try again.