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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Dan Schmidt <dfan@d...>
Subject: [Caml-list] Design advice
I've been using ocaml for only a couple of months now, and it's not
yet clear to me how to do some things most idiomatically in it.

One has to do with making the equivalent of an enum in C.  Say I'm
implementing a deck of cards for a card game.  There are four suits,
and none of them have any special properties (this isn't a game like
bridge where different suits are treated differently).  I could do

  type suit = Spades | Hearts | Diamonds | Clubs

but this seems a little heavyweight; it seems weird to perform pattern
matching on values that really have no semantic importance other than
the fact that they are different from each other.  It's not like I'm
going to have any code that does one thing when given the 3 of Spades
and another thing when given the 3 of Hearts.  The other issue is that
it is mildly annoying to, for example, write a compare function to be
used inside a struct that implements the OrderedType signature (e.g.,
if I want to have a Set of cards).

The alternative is to just use an int, but then it is theoretically
possible that I could pass in ints outside the valid range and get
run-time errors.  The idea of guaranteeing that a suit is never
invalid appeals to me.

The same sort of issue comes up with representing the two players of
the game.  I could use an int and just raise exceptions everywhere if
it turns out to be not 0 or 1.  Or I could make a

  type player = Player_one | Player_two

type, but now I have to convert this to an integer whenever I want to
use the player number as an index.  Which sort of approach usually
ends up being less of a hassle in the end?  Or does it depend on the
particular application?  Or is there yet a third solution which is
better than either of these?  I've been vacillating, and right now I
am inclined to go with the variants at the expense of having to
indirect every once in a while.

Finally, is there any type in the library that functions like an
immutable array?  I would like to have an indexable bunch of values
but use it in a purely functional way.  I could always just use
Arrays and copy them before updating, but if there's already an
idiomatic type to use I'd prefer to use that.

Thanks,
Dan

-- 
http://www.dfan.org
-------------------
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