我是Haskell的新手,到目前为止,我一直很喜欢它,但是我在IO的某些方面感到很挣扎。 我正在制作一种简单的“ Akinator”应用程序,但在理解如何使用IO递归修改二进制树时遇到了麻烦。 我有自己的数据类型:
data QA = P String | Q QA String QA -- P representing person, Q representing a question
deriving (Show, Read)
我们通过回答是或否来回答问题。是的将您带到左边,否的则将您带到右边。 但是,当我运行程序(到达一个人)时到达树的末端时,我希望能够通过添加另一个质量检查来修改树。 (如果找不到此人,我们会要求用户输入)
我使用的功能是:
play :: QA -> IO QA
如何在递归过程中将QA数据类型转换为IO QA,并返回相同的QA(以IO格式),但是增加了Leaf / Branch?
非常感谢您!
---------我的一些代码--------
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)
答案 0 :(得分:2)
你可以写
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)