Version franaise
Home About Download Resources Contact us

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

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: 2010-06-07 (18:32)
From: Török Edwin <edwintorok@g...>
Subject: Re: [Caml-list] Converting variants with only constant constructors to integers
On 06/07/2010 09:31 PM, Török Edwin wrote:
> On 06/07/2010 09:23 PM, Wojciech Meyer wrote:
>> Török Edwin <> 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
> Yes, I probably should have started with that.
> I have some flags like:
> type myflags = Property1 | Property2 | Property3;;
> I have something similar code in C, as an enum.
> I need to convert to convert OCaml lists of flags to an integer, that
> will ultimately be passed to a C function.
> So [Property1; Property3] needs to become (1 << Property1) | (1 <<
> Property3). I want to do this conversion in OCaml code.
> Important is that "Property1" from OCaml gets the same value as
> Property1 in the C enum.
>> , and
>> then maybe there are other solutions to your problem.
>> Most likely Marshal module from stdlib, will full-fill your requirements.
> If I only had OCaml code to deal with yes, but see above.
>> I can imagine you could use an association list, function with pattern
>> matching
> I don't have too many flags, so I could write a simple pattern matching
> function to convert to int (even manually).
> I just thought there is a way to do this easily, and more general than that.
>> , 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.
> How about the hash value? I guess no guarantees about that either.
> Best regards,
> --Edwin