Animal guessing game - critique my code
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
On 10/29/06, JTXX <jtxx000@yahoo.co.uk> wrote:
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.
All of your code lives in the IO monad. It's usually considered a good idea to split your program into "IO" and "logic". Do as much as possible outside of the IO monad (i.e. in functions which don't have an IO type). -- Sebastian Sylvan +46(0)736-818655 UIN: 44640862
participants (2)
-
JTXX -
Sebastian Sylvan