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: David Allsopp <dra-news@m...>
Subject: RE: [Caml-list] Converting variants with only constant constructors to integers
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.


David