caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* Union of type variables
@ 2009-01-31 16:55 Dario Teixeira
  2009-02-02 17:07 ` [Caml-list] " Dario Teixeira
  0 siblings, 1 reply; 2+ messages in thread
From: Dario Teixeira @ 2009-01-31 16:55 UTC (permalink / raw)
  To: caml-list

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)

Thanks in advance!
Best regards,
Dario Teixeira






^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: [Caml-list] Union of type variables
  2009-01-31 16:55 Union of type variables Dario Teixeira
@ 2009-02-02 17:07 ` Dario Teixeira
  0 siblings, 0 replies; 2+ messages in thread
From: Dario Teixeira @ 2009-02-02 17:07 UTC (permalink / raw)
  To: caml-list

Hi,

> 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)

In the meantime I realised what the problem was.  I neglected to take
into account the open nature of polymorphic variants, meaning that as
long as the phantom type variable is open, then the following code is
enough to do what I want:

val union: 'a t -> 'a t -> 'a t
let union x y = Union (x, y)


Cheers,
Dario Teixeira






^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2009-02-02 17:07 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2009-01-31 16:55 Union of type variables Dario Teixeira
2009-02-02 17:07 ` [Caml-list] " Dario Teixeira

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).