Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] enums in OCaml?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: David Mentre <David.Mentre@i...>
Subject: Re: [Caml-list] enums in OCaml?
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 = <fun>
# 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 = <fun>


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