A minimalistic implementation of the Hangman game in Haskell

Hello everyone,
I was just playing around with Haskell and I’ve realized a simple Hangman game.
I’m very new with Haskell, so I’ve certainly made some mistakes 🙂

Here’s the code:

import System.IO

revealChar (x:[]) secretWord partialWord =
           zipWith (\ s p -> if x == s then s else p) secretWord partialWord
revealChar xs secretWord partialWord =
           if xs == secretWord then secretWord else partialWord

getSecretWord = do
              sBuff <- openFile "secretWords.txt" ReadMode
              inpStr <- hGetLine sBuff
              hClose sBuff
              return inpStr

playGame 0 secret partial = do putStrLn "I'm sorry, you have lose!"
playGame t secret partial = do
          putStrLn $ "=> " ++ partial
          putStrLn $ "Tell the a single letter or the entire word. " ++ (show t) ++ " tries left."
          charStr <- getLine
          if secret == partial
             then putStrLn "You have win!"
             else playGame (t-1) secret (revealChar charStr secret partial)

main = do
     secretWord <- getSecretWord
     let partialWord = foldl1 (++) (replicate (length secretWord) "_")
     putStrLn "Welcome to the useless Hangman Game!"
     putStrLn ("Today's word is: " ++ partialWord)
     playGame (length partialWord) secretWord partialWord</pre>

I must confess, I begin to like Haskell and his weird syntax. This version is very readable and compact in my opinion. There are some tricks of FP I want to show you in this code:

  1. The pattern matching magic allows the revealChar function to be reusable to both guess entire word or check a single character. Maybe revealChar it’s a violation of the FP pure functions?
  2. Anonimous functions are in my opinion a very elegant way to make your code smaller and cleaner.
  3. The secret word is stored in a separate file, so no spoiler at all 🙂
  4. You can run this saving it into a .hs file and running runghc <yourfile>

I’m looking forward to go deeper in Haskell 🙂




    Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

    Logo WordPress.com

    Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

    Foto Twitter

    Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

    Foto di Facebook

    Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

    Google+ photo

    Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

    Connessione a %s...