Haskell Assignment 2: The Animals Game
Fall 2010, David Matuszek

Purposes of this assignment

General idea of the assignment

The Animals Game is a form of Twenty Questions (although there is no limit on the number of questions). Traditionally, the text-based version goes something like this:

Computer: Think of an animal. Hit Return when you're ready.
Human: (hits return)
Computer: Does your animal live in the water?
Human: No
Computer: Does it have stripes?
Human: No
Computer: I know! Is your animal a horse?
Human: No
Computer: OK, what is your animal?
Human: A turtle
Computer: What question would distinguish your animal from a horse?
Human: Does it have a shell?
Computer: What is the answer for a turtle?
Human: Yes
Computer: Thanks, I'll remember that! Would you like to play again?

And the computer does remember that. If the human (or any other human) plays again, the program will know that a turtle is one of the possible answers.

(By the way: If the computer gets the right answer, the traditional response is: "See? Humans should work, computers should think!")

Details

Your task is to write a Haskell program to play this game. Save the animals "learned" on a file that is read in when the program starts and written out when the program ends. You can use a fixed name (such as data.txt) for the saved file.

Starter code

I am providing a small amount of "starter code," which you can use, modify, or ignore--it's up to you.

data Tree = Answer String | Question String Tree Tree deriving (Show)

animals = Question "Does it live in the water?"
            ((Question "Does it hop?") (Answer "frog") (Answer "fish"))
            (Answer "cow")
            
main = do
    putStr "Think of an animal. Hit Enter when you are ready.  "
    _ <- getLine
    ask animals

ask :: Tree -> IO ()
ask (Question q yes no) = do
        putStrLn q
        answer <- getLine
        if answer == "yes" then ask yes
                           else ask no
ask (Answer a) = do
        putStrLn $ "I know! It's a " ++ a ++ "!"

Suggestions

You might want to start each line in the data file with an indication of where to put the text in the animals Tree. For example, yyny could stand for "yes, yes, no, yes."

Learn You a Haskell for Great Good talks about inserting nodes into a binary tree. You might be able to use some of that code.

Due date

Tuesday, November 16, before midnight. Please just zip up Haskell program and data file and submit it via Blackboard.