Version française
Home     About     Download     Resources     Contact us    
Browse thread
Converting variants with only constant constructors to integers
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Török_Edwin <edwintorok@g...>
Subject: Converting variants with only constant constructors to integers
Hi,

What is the recommended way to convert a variant that has only constant
constructors to an integer? (an integer that is unique for each constant
constructor, preferably sequential in the order in which they are declared).

I found the following two possibilities, but I am not sure if these are
guaranteed to return the same results for future versions of OCaml or not:

let int_of_constant_variant a : int = Hashtbl.hash a;;
let int_of_constant_variant a : int =
 let r = Obj.repr a in
  assert (Obj.is_int r);
  (Obj.magic r : int);;

for 'type t = A | C | B', both of these functions return 0,1, and 2 for
A,C, and B respectively.

Best regards,
--Edwin