From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Delivered-To: caml-list@yquem.inria.fr Received: from concorde.inria.fr (concorde.inria.fr [192.93.2.39]) by yquem.inria.fr (Postfix) with ESMTP id 260B3BC48 for ; Fri, 25 Mar 2005 20:13:53 +0100 (CET) Received: from postfix4-2.free.fr (postfix4-2.free.fr [213.228.0.176]) by concorde.inria.fr (8.13.0/8.13.0) with ESMTP id j2PJDqTN015471 for ; Fri, 25 Mar 2005 20:13:53 +0100 Received: from localhost.localdomain (idea.homelinux.org [82.227.14.139]) by postfix4-2.free.fr (Postfix) with ESMTP id A98302EC963; Fri, 25 Mar 2005 20:13:52 +0100 (CET) Received: from kim by localhost.localdomain with local (Exim 4.50) id 1DEuHn-0000sV-Vy; Fri, 25 Mar 2005 20:16:00 +0100 Subject: Re: [Caml-list] generic data type -> int function From: Kim Nguyen To: Hal Daume III Cc: Caml Mailing List In-Reply-To: References: Content-Type: text/plain; charset=ISO-8859-15 Content-Transfer-Encoding: quoted-printable Organization: Laboratoire de Recherche en Informatique Date: Fri, 25 Mar 2005 20:15:59 +0100 Message-Id: <1111778159.3062.21.camel@localhost.localdomain> Mime-Version: 1.0 X-Mailer: Evolution 2.0.4 X-Miltered: at concorde with ID 424462F0.000 by Joe's j-chkmail (http://j-chkmail.ensmp.fr)! X-Spam: no; 0.00; caml-list:01 lri:01 integers:01 hashtbl:01 hash:01 constructors:01 hashtbl:01 hash:01 val:01 foo:01 ...:98 polymorphic:01 constructor:01 constructor:01 int:01 X-Spam-Checker-Version: SpamAssassin 3.0.2 (2004-11-16) on yquem.inria.fr X-Spam-Status: No, score=0.1 required=5.0 tests=FORGED_RCVD_HELO autolearn=disabled version=3.0.2 X-Spam-Level: Le jeudi 24 mars 2005 =E0 08:38 -0800, Hal Daume III a =E9crit : > Hi all -- >=20 > Is there a straightforward way (or a built in function, or...) to=20 > automatically map an enumerated data type to integers (and back, if=20 > possible, but that's not strictly necessary). In particular, I need=20 > something like: Hi, you can use the polymorphic function : Hashtbl.hash_param which happens to map constructors to their internal tag. You should be aware that this is only a (cool) side-effect of =09 the current implementation and could change in the future. This is a bit of a hack but prevents you from using Obj.magic or automatically generating pattern matching (which you should regenerate every time you change the type). # type t =3D A | B | C | D of int | E of string | G;; type t =3D A | B | C | D of int | E of string | G # let to_int x =3D Hashtbl.hash_param 1 1 x;; val to_int : 'a -> int =3D # to_int A;; (* first constant constructor *) - : int =3D 0 # to_int B;; - : int =3D 1 # to_int C;; - : int =3D 2 # to_int (D(42));; (* first non-constant constructor *) - : int =3D 0 # to_int (E("foo"));; - : int =3D 1 # to_int G;; - : int =3D 3=09 Regards, --=20 Kim