Browse thread
[Caml-list] Design advice
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | William Lovas <wlovas@s...> |
| Subject: | Re: [Caml-list] Design advice |
On Sat, Sep 28, 2002 at 03:55:43AM -0700, Chris Hecker wrote:
> >type, but now I have to convert this to an integer whenever I want to
> >use the player number as an index.
>
> type suit = Spades | Hearts | Diamonds | Clubs
>
> let suit_to_int (s : suit) =
> assert (Obj.is_int (Obj.repr s));
> ((Obj.magic s) : int)
>
> The assert will catch it if you add variables to one of the constructors
> and then call this. This uses magic, which is bad, but it alleviates you
> having to type the variant constructors again and possibly make an error in
> the assocation with the int, which is good. Pick your poison.
Wouldn't it be safer to just do something like:
let suit_to_int = function
| Spades -> 0
| Hearts -> 1
| Diamonds -> 2
| Clubs -> 3
? You only have to type it once, and if you change the constructors
around, it won't even compile. Plus it gives you control over which
int a suit corresponds to -- i doubt you can get any sort of guarantee
if you use Obj.magic.
William
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners