English version
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.

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 <cez@pkl.net> 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: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr