Browse thread
generic data type -> int function
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Kim Nguyen <Kim.Nguyen@l...> |
| Subject: | Re: [Caml-list] generic data type -> int function |
Le jeudi 24 mars 2005 à 08:38 -0800, Hal Daume III a écrit :
> Hi all --
>
> 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). In particular, I need
> something like:
Hi,
you can use the polymorphic function : Hashtbl.hash_param
which happens to map constructors to their internal tag.
You should be aware that this is only a (cool) side-effect of
the current implementation and could change in the future.
This is a bit of a hack but prevents you from using Obj.magic
or automatically generating pattern matching (which you should
regenerate every time you change the type).
# type t = A | B | C | D of int | E of string | G;;
type t = A | B | C | D of int | E of string | G
# let to_int x = Hashtbl.hash_param 1 1 x;;
val to_int : 'a -> int = <fun>
# to_int A;; (* first constant constructor *)
- : int = 0
# to_int B;;
- : int = 1
# to_int C;;
- : int = 2
# to_int (D(42));; (* first non-constant constructor *)
- : int = 0
# to_int (E("foo"));;
- : int = 1
# to_int G;;
- : int = 3
Regards,
--
Kim