From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from majordomo@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id LAA19897; Wed, 13 Jun 2001 11:51:25 +0200 (MET DST) Received: (from weis@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id LAA19669 for caml-list@pauillac.inria.fr; Wed, 13 Jun 2001 11:51:24 +0200 (MET DST) Received: from concorde.inria.fr (concorde.inria.fr [192.93.2.39]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id JAA16562 for ; Wed, 13 Jun 2001 09:37:14 +0200 (MET DST) Received: from pochi.inria.fr (pochi.inria.fr [128.93.8.128]) by concorde.inria.fr (8.11.1/8.10.0) with ESMTP id f5D7bCT14388; Wed, 13 Jun 2001 09:37:12 +0200 (MET DST) Received: (from mentre@localhost) by pochi.inria.fr (8.11.1/8.10.0) id f5D7bCE26811; Wed, 13 Jun 2001 09:37:12 +0200 X-Authentication-Warning: pochi.inria.fr: mentre set sender to David.Mentre@inria.fr using -f To: leary@nwlink.com Cc: caml Subject: Re: [Caml-list] enums in OCaml? References: <20010612192126.B24440@jean> From: David Mentre Date: 13 Jun 2001 09:37:12 +0200 In-Reply-To: <20010612192126.B24440@jean> Message-ID: User-Agent: Gnus/5.0808 (Gnus v5.8.8) Emacs/20.4 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk leary@nwlink.com writes: > What's the right way to make something like C's enums in OCaml. I found a > couple references to sum types online and in the manual and caml light > tutorial, but none of it was really what I'm looking for: alias a number > with a name, hopefully conveniently. sum type and pattern matching is really what you are looking for: # type my_enum = Case1 | Case2 | Case3;; type my_enum = Case1 | Case2 | Case3 # let num c = match c with Case1 -> 1 | Case2 -> 2 | Case3 ->3 ;; val num : my_enum -> int = # num Case3;; - : int = 3 Usually, you do not need to call the num function, you can use the symbolic name directly in your code. And at the opposite of C enum, if a case is forgotten, the compiler warns you (usefull when you extend your enum): # let faulty_num c = match c with Case1 -> 1 | Case2 -> 2;; Warning: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: Case3 val faulty_num : my_enum -> int = Best regards, d. -- David.Mentre@inria.fr -- http://www.irisa.fr/prive/dmentre/ Opinions expressed here are only mine. ------------------- Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr