[Haskell-cafe] Hangman game

Yitzchak Gale gale at sefer.org
Sat Jan 19 18:21:26 EST 2008


Hi Ronald,

Ronald Guida wrote:
> I'm interested in learning how to program games.  Since I have to start
> somewhere, I decided to write a simple Hangman game.  I'm wondering if
> anyone can look at my code and give me some feedback.

Lots of fun, thanks! And nicely written.

One point is that while it's OK to do your random
calculation directly in IO for this simple case, in general
you will have many random calculations and you will
want to avoid forcing them all into IO.

You can add one more field to GameState that holds
a random generator. Let's say you call it gsRandGen.
Make sure that gsRandGen gets initialized somewhere.

Define this utility function:

rand :: MonadState GameState m => (StdGen -> (a, StdGen)) -> m a
rand f = do
  gs <- get
  let (x, g) = f $ gsRandGen gs
  put $ gs {gsRandGen = g}
  return x

Now, instead of:

>   nWord <- liftIO $ getStdRandom (randomR (0,length wordList - 1))

you can write:

>   nWord <- rand $ randomR (0,length wordList - 1)

If you want, you can even remove the dependence on
StdGen by making some of your function types polymorphic,
qualified where necessary by RandomGen g => ...

Regards,
Yitz


More information about the Haskell-Cafe mailing list