[Haskell-cafe] Hangman game

Paul Johnson paul at cogito.org.uk
Sun Jan 20 12:08:49 EST 2008

Ronald Guida wrote:
> Hi,
> 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.
Nicely written.  The design reads very much like a straight translation 
from the imperative style, which is why so much of it is in the IO 
monad.  There is nothing wrong with this for a simple game like Hangman, 
but for larger games it doesn't scale.  So here are a few pointers to 
ways of rewriting it to keep the IO to the top level and the actual work 
in a functional style:

1: Your GameState type can itself be made into a monad.  Take a look at 
the "All About Monads" tutorial, especially the State monad.  Think 
about the invariants in GameState; can you produce a new monad that 
guarantees these invariants through a limited set of actions.  How do 
these actions correspond to user perceptions?

2: You can layer monads by using monad transformers.  Extend the 
solution to part 1 by using StateT IO instead of just State.

3: Your current design uses a random number generator in the IO monad.   
Someone already suggested moving that into the GameState.  But you can 
also generate an infinite list of random numbers.  Can you make your 
game a function of a list of random numbers?

4: User input can also be considered as a list.  Haskell has "lazy 
input", meaning that you can treat user input as a list that actually 
only gets read as it is required.  Can you make your game a function of 
the list of user inputs?  How does this interact with the need to 
present output to the user?  What about the random numbers?

Good luck,


More information about the Haskell-Cafe mailing list