2

I'm new to Haskell and I'm loving it so far, but I'm struggling with some aspects of IO. I'm making a sort of simple "Akinator" application and I'm having trouble understanding how to modify a binary tree using IO recursion. I have my own data type:

data QA = P String | Q QA String QA   -- P representing person, Q representing a question
 deriving (Show, Read)

We go down the tree by answering a question with yes or no. Yes takes you to the left and no takes you to the right. But when I get to the end of the tree while we run the program (we reach a person), I want to be able to modify the tree by adding another QA. (We ask the user for input in case the person was not found)

The function i use is:

play :: QA -> IO QA

How do you convert the QA data type to a IO QA during the recursion and return the same QA (in IO format) but with an added Leaf/Branch?

Thank you very much!

-------Some of my code--------

play :: QA -> IO QA
play (P s) = do
   a <- yesNoQuestion ("Is ( " ++s ++" ) your person?")
   case a of
      True -> do
          putStrLn "I win omg so ez!"
          exitSuccess -- (to exit the application without modifying
                      -- dunno if this is a good solution)
      False -> do
        p <- question "Just curious: Who was your famous person?"
        n <- question "Give me a question for which the answer for this person is yes"
        return q -- (Here I want to return a new QA with an added question -- 
                 --and with a leaf representing a person)


play (Q qaY s qaN) = do
    a <- yesNoQuestion s
    case a of
        True -> do
            pY <- play qaY
            return pY -- (I want this to say (return Q pY s qaN) But this 
                      -- does not work 
          --  since all types aren't IO)
        False -> do
            pN <- play qaN
            return pN -- (Same as previous)

1 Answer 1

2

You can write

            return (Q pY s qaN)

play (Q qaY s qaN) = do
    a <- yesNoQuestion s
    case a of
        True -> do
            pY <- play qaY
            return (Q pY s qaN)
        False -> do
            pN <- play qaN
            return (Q qaY s pN)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.