Version française
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-08 (07:43)
From: David Allsopp <dra-news@m...>
Subject: RE: [Caml-list] Converting variants with only constant constructors to integers
W Dan Meyer wrote:
> bluestorm <> writes:
> > Beware that "%identity" is an unsafe feature that breaks all safety
> > guarantees if used badly.
> Yes %identity is another solution. Although as safe as Obj.magic.

It's a bit pedantic but the %identity *primitive* is not the evil thing -
what is evil about Obj.magic is that it has an illegal type, namely 'a ->
'b. %identity constrained to a type like foo -> int is a safe use of it
(obviously with the side-condition that foo only has constant constructors,
as noted - but that's a local check, i.e. in your code, not your callers').

Incidentally, the general function for getting a unique integer for a
variant type with non-constant constructors isn't that bad either:

let int_of_gen x =
  let x = Obj.repr x
    if Obj.is_block x
    then -1 * Obj.tag x - 1
    else (Obj.magic x : int) 

Naturally, any specific use should constrain the type of this function
beyond 'a -> int