On 06/07/2010 09:48 PM, David Allsopp wrote:
> Török Edwin wrote:
>> 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).
> 
> type foo = A | B;;
> external int_of_foo : foo -> int = "%identity";;
> 
> Which is another way of saying Obj.magic - but %identity is an OCaml
> primitive, where Obj.magic is part of a restricted module so there is a
> small semantic difference in terms of future support. The internal
> representation of variants won't change until at least OCaml 4.0.0 -
> there're simply far too many C bindings out there! foo_of_int obviously
> can't be done quite so trivially written although having checked that the
> int represents a valid constructor you can then use %identity in the same
> way.

Thanks, that "%identity" looks exactly what I wanted.
I don't need a foo_of_int right now.

On 06/07/2010 09:45 PM, bluestorm wrote:
> 2010/6/7 W Dan Meyer <wojciech.me...@googlemail.com
> <mailto:wojciech.me...@googlemail.com>>
>> I can imagine you could use an association list, function with pattern
>> matching, code generation tool (based on CamlP4), etc.
>
> I wrote a type-conv (
> http://www.ocaml.info/home/ocaml_sources.html#type-conv ) generator for
> just that a few years ago :
>    http://bluestorm.info/camlp4/ty_enum_to_int.ml.html
>
> Example use :
>
>   type test = | A | B | C | D of bool with to_int
>
>
> Generated functions :
>
>   let test_to_int = function | A -> 0 | B -> 1 | C -> 2 | D _ -> 3
>
>   let test_of_int = function
>   | 0 -> A
>   | 1 -> B
>   | 2 -> C
>   | 3 -> failwith "can't convert to a constructor with parameters: D"
>   | _ -> invalid_argument "test_of_int"
>

If I'll need a foo_of_int this sounds like a good solution, thanks.

Best regards,
--Edwin

_______________________________________________
Caml-list mailing list. Subscription management:
http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
Archives: http://caml.inria.fr
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs

Reply via email to