Accueil     À propos     Téléchargement     Ressources     Contactez-nous

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Union of type variables
• Dario Teixeira
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2009-01-31 (16:55) From: Dario Teixeira Subject: Union of type variables
```Hi,

Consider the following toy experiment with phantom types.  Note that the shown
implementation of function "union" is far from optimal; though it takes only
two arguments, these are being passed as a list.  This is basically just a
kludge that forces the phantom type in the return type to be also a union.

module M:
sig
type 'a t

val a: int -> [> `Foo ] t
val b: int -> [> `Foo ] t
val c: int -> [> `Bar ] t
val d: int -> [> `Bar ] t

val union: 'a t list -> 'a t
end =
struct
type foobar_t =
| A of int
| B of int
| C of int
| D of int
| Union of foobar_t * foobar_t

type 'a t = foobar_t

let a x = A x
let b x = B x
let c x = C x
let d x = D x

let union (x :: y :: []) = Union (x, y)
end

Obviously I would like to get rid of this kludge.  The signature and
implementation for "union" should be something like the (syntactically
incorrect) code below.  But is it at all possible to declare an union
of type variables?  (which presupposes they are polymorphic variants)

val union: 'x t -> 'y t -> [> 'x | 'y ] t
let union x y = Union (x, y)