English version
Accueil     Ŕ propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis ŕ jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml ŕ l'adresse ocaml.org.

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 <bluestorm.dylc@gmail.com> 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