Version française
Home     About     Download     Resources     Contact us    

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

Browse thread
[Caml-list] Allowing many types
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-02-08 (16:53)
From: Remi VANICAT <vanicat@l...>
Subject: Re: [Caml-list] Allowing many types
Ceri Storey <> writes:

> I've been trying to do something similar with something i'm writing, and
> the only thing i could come up with is to store data in an object, and
> then subclass it. The problem here is that once the object has been
> coerced to the general type, it cannot be coerced back again. ie: if you
> subclass the object to say, impliment integers, then it's not possible
> for it to be coerced back to the integer type so you can retreive / act
> on the value. (withoug using Obj.magic, that is)
> If anyone has any good ideas, I'd be happy to hear about them too.

polymorphic variant me be the answer, because you can get back the
type :

let fn1 (`Int x) = float_of_int x
let fn2 (`Float x) = x

let fn x =
  match x with
  | `Int _ as i -> fn1 i
  | `Float _ as f -> fn2 f
  | _ -> raise (Invalid_argument "fn")

(be aware that

let fn x =
  match x with
  | `Int _ as i -> fn1 x
  | `Float _ as f -> fn2 x
  | _ -> raise (Invalid_argument "fn")

doesn't work)

extensible function from camlp4 library may be also useful, but
I've not try it yet.

Rémi Vanicat
Bug reports:  FAQ:
To unsubscribe, mail  Archives: