This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

Polymorphic Variants
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2007-01-17 (06:44) From: skaller Subject: Re: [Caml-list] Polymorphic Variants
```On Wed, 2007-01-17 at 11:19 +0900, Jacques GARRIGUE wrote:

> If you mean that, without type annotations, types and errors become
> very hard to read, this is true, but the manual explicitely encourages
> to add type annotations :-)

You are not kidding .. and even type annotations don't always help.
I regularly get 100-200 line errors, even in cases where the compiler
clearly knows which tag is causing the problem.

But I would not give up the polymorphic variants despite this pain,
because the alternative is now unthinkable.

Basically, with ordinary variants if you have some subset
of cases you can handle it easily but verbosely with
morphisms:

type X = | A | B | C | D
type Y = | AA | BB

let XtoY x : Y = match x with
| A -> AA
| B -> BB
| _ -> failwith "blah"

let YtoX y : X = match y with
| AA -> A
| BB -> B

With polymorphic variants these morphisms are created automatically,
and AFAIK the embedding (YtoX) has zero cost. You can also do:

type X = [`A | `B | `C | `D]
type Y = [`A | `B]

let XtoY x: Y = match x with
| #Y as y -> (y:X:>Y)
| _ -> failwith "khg"

let YtoX y: X = (y:Y:>X)

This is mainly "syntactic sugar". The recursive case is where
polymorphic variants really shine, eg a compiler "expression"
type with various "sub expression" types where there are constraints
satisfied recursively by all nodes. (These things are still far too
hard to define with multiple parameters though .. ;(

--
John Skaller <skaller at users dot sf dot net>
Felix, successor to C++: http://felix.sf.net

```