[Haskell] Animal guessing game - critique my code

JTXX jtxx000 at yahoo.co.uk
Sat Oct 28 20:04:00 EDT 2006


Hello everybody.

I'm trying to learn Haskell, and so I implemented the
classic animal guessing game.  However, I feel that
there is probably a more elegant implementation than
the one shown below, so any suggestions for
improvement would be great.

Cheers,
Caleb

\begin{code}
data GuessTree = Answer String
               | GuessTreeQuestion {guessTreeQuestion
:: String, guessTreeNo, guessTreeYes ::GuessTree}

askQuestion :: String -> IO Bool
askQuestion str = do
  putStrLn str
  response <- getLine
  return $ isYes response
  where isYes ('y':xs) = True
        isYes _ = False

runTree :: GuessTree -> IO GuessTree
runTree (Answer name) = do
  response <- askQuestion $ "Is it a " ++ name ++ "?"
  if response
    then do putStrLn "Ha!"
            return $ Answer name
    else do putStrLn "What is it?"
            animal <- getLine
            putStrLn $ "Enter a question to help
distinguish between a " ++ name ++ " and a " ++ animal
            question <- getLine
            a <- askQuestion $ "Is the answer yes for
" ++ animal ++ "?"
            (if a then id else flip) (\n y -> return $
GuessTreeQuestion {guessTreeQuestion = question,
guessTreeNo = n, guessTreeYes = y}) (Answer animal)
(Answer name)
runTree GuessTreeQuestion {guessTreeQuestion = ques,
guessTreeYes = yesTree, guessTreeNo = noTree} = do
  response <- askQuestion $ ques
  if response
    then do a <- runTree noTree
            return $ GuessTreeQuestion
{guessTreeQuestion = ques, guessTreeNo = a,
guessTreeYes = yesTree}
    else do a <- runTree yesTree
            return $ GuessTreeQuestion
{guessTreeQuestion = ques, guessTreeNo = noTree,
guessTreeYes = a}

run :: GuessTree -> IO GuessTree
run tree = do
  putStrLn "Think of an animal and press enter."
  getLine
  a <- runTree tree
  r <- askQuestion "Play again?"
  if r then run a else return a

main = run $ Answer "bear"
\end{code}

Send instant messages to your online friends http://uk.messenger.yahoo.com 


More information about the Haskell mailing list