Version française
Home     About     Download     Resources     Contact us    
Browse thread
generic data type -> int function
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jean-Christophe Filliatre <Jean-Christophe.Filliatre@l...>
Subject: Re: [Caml-list] generic data type -> int function

Hi,

 > Is there a straightforward way (or a built in function, or...) to 
 > automatically map an enumerated data type to integers (and back, if 
 > possible, but that's not strictly necessary).  

I don't think there such  a built-in function.  But using Obj.magic to
convert  constant  constructors  to  integers is  safe  (the  constant
constructors of a type are represented by integers starting from 0):

======================================================================
# type t = A|B|C|D;;
type t = A | B | C | D
# (Obj.magic A : int);;
- : int = 0
# (Obj.magic D : int);;
- : int = 3
======================================================================

Going the  way back  obviously requires a  dynamic check  (the integer
needs to be within the right bounds).

Note that I  do not encourage the use of Obj.magic.  I even think that
writing your own function to  convert constructors to integers will be
equally fast (since pattern-matching is compiled using a constant time
lookup table in this case); and you can macro-generate such functions.

Hope this helps,
-- 
Jean-Christophe