Understanding polymorphic variants

[Starting a new thread on grounds that New Draft Tutorial on Polymorphic Variants is for feedback on the tutorial]

Exploring polymorphic variants I tried this:

 # let f = function
| `Cat -> "pet"
| `Dog -> "pet"
| 99 -> "other" ;;
Error: This pattern matches values of type int
       but a pattern was expected which matches values of type [? `Cat | `Dog ]

I have not come across [? ...] in the documentation. What does it mean? (I expected 99 to cause an error, but the message surprised me.)

Gregg

2 Likes

Isn’t it that the thing that shall not be named couldn’t decide if the pattern matching creates a closed or an open polymorphic variant and, therefore, prints a question mark?

The ? symbol means that it is unknown if the polymorphic variant type should be open like in

let f = function
| `Cat -> ()
| `Dog -> ()
| _ -> ()

where f has type [> `Cat | `Dog ] -> unit or closed like in

let f = function
| `Cat -> ()
| `Dog -> ()

where the type of f is [< `Cat | `Dog ] -> unit.
Since the typing of the pattern matching was interrupted by the 99 type error, it is not possible to decide between the two cases, leading thus to the type [? `Cat | `Dog ] appearing in the error message.
In a fully unicode compatible word, I may propose to replace ? with [≶? `Cat | `Dog ]

3 Likes