我是 Haskell 新手,正在编写一个简单的 AI 决策系统来玩 20 个问题风格的游戏。如果程序无法猜测正确答案,它将询问一个问题来区分答案,并将该问题存储在树中。它在程序开始时从文件系统读入树,并在程序结束时将其写回。
我在 Haskell 中的序列化代码方面遇到了很多问题。我收到错误“前奏读取:未解析”。这是怎么回事?这是我的代码:
import Data.Char
import System.IO
-- Defines a type for a binary tree that holds the questions and answers
data Tree a =
Answer String |
Question String (Tree a) (Tree a)
deriving (Read, Show)
-- Starts the game running
main = do
let filePath = "data.txt"
fileContents <- readFile filePath
animals <- return (read fileContents)
putStrLn "Think of an animal. Hit Enter when you are ready. "
_ <- getLine
ask animals
writeFile filePath (show animals)
-- Walks through the animals tree and ask the question at each node
ask :: Tree a -> 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! Is your animal a " ++ a ++ "?"
answer <- getLine
if answer == "yes" then computerWins
else playerWins
computerWins = do putStrLn "See? Humans should work, computers should think!"
playerWins = do putStrLn "TODO"
这是我正在使用的数据文件:
Question "Does it live in the water?"
((Question "Does it hop?") (Answer "frog") (Answer "fish"))
(Answer "cow")
最佳答案
read
并不是为了稳健地处理额外括号之类的事情。您的代码适用于我使用以下数据文件:
Question "Does it live in the water?"
(Question "Does it hop?" (Answer "frog") (Answer "fish"))
(Answer "cow")
关于parsing - 调试Haskell读取函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4196611/