From: Jean-Christophe Filliatre <Jean-Christophe.Filliatre@lri.fr>
To: Hal Daume III <hdaume@ISI.EDU>
Cc: Caml Mailing List <caml-list@yquem.inria.fr>
Subject: Re: [Caml-list] generic data type -> int function
Date: Fri, 25 Mar 2005 12:37:04 +0100 [thread overview]
Message-ID: <16963.63456.885441.571929@gargle.gargle.HOWL> (raw)
In-Reply-To: <Pine.LNX.4.44.0503240834530.1827-100000@albini.isi.edu>
Hi,
> Is there a straightforward way (or a built in function, or...) to
> automatically map an enumerated data type to integers (and back, if
> possible, but that's not strictly necessary).
I don't think there such a built-in function. But using Obj.magic to
convert constant constructors to integers is safe (the constant
constructors of a type are represented by integers starting from 0):
======================================================================
# type t = A|B|C|D;;
type t = A | B | C | D
# (Obj.magic A : int);;
- : int = 0
# (Obj.magic D : int);;
- : int = 3
======================================================================
Going the way back obviously requires a dynamic check (the integer
needs to be within the right bounds).
Note that I do not encourage the use of Obj.magic. I even think that
writing your own function to convert constructors to integers will be
equally fast (since pattern-matching is compiled using a constant time
lookup table in this case); and you can macro-generate such functions.
Hope this helps,
--
Jean-Christophe
next prev parent reply other threads:[~2005-03-25 11:37 UTC|newest]
Thread overview: 11+ messages / expand[flat|nested] mbox.gz Atom feed top
2005-03-24 16:38 Hal Daume III
2005-03-25 11:37 ` Jean-Christophe Filliatre [this message]
2005-03-30 3:26 ` [Caml-list] " Hal Daume III
2005-03-30 22:27 ` Oliver Bandel
2005-03-31 14:33 ` Hal Daume III
2005-03-31 17:01 ` Richard Jones
2005-03-31 18:04 ` Hal Daume III
2005-03-30 22:29 ` Oliver Bandel
2005-03-31 14:33 ` Hal Daume III
2005-03-25 19:15 ` Kim Nguyen
2005-03-29 7:29 ` Oliver Bandel
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=16963.63456.885441.571929@gargle.gargle.HOWL \
--to=jean-christophe.filliatre@lri.fr \
--cc=caml-list@yquem.inria.fr \
--cc=hdaume@ISI.EDU \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox