[
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: | W Dan Meyer <wojciech.meyer@g...> |
| Subject: | Re: [Caml-list] Converting variants with only constant constructors to integers |
Török Edwin <edwintorok@gmail.com> writes: > 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). In the first play you'd need to tell us, why would you need this, and then maybe there are other solutions to your problem. Most likely Marshal module from stdlib, will full-fill your requirements. I can imagine you could use an association list, function with pattern matching, code generation tool (based on CamlP4), etc. The later would be needed if you have varied data structure, that change frequently or it is too big to maintain it with just pattern matching. > > 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);; There is no guarantee of these kind of unsafe casts at all (means using Obj.magic). Especially Obj.magic should not be used in marshaling, but most common patter is for type system tricks. Wojciech