我是Haskell的新手,我正在编写一个简单的AI决策系统来玩20问题的游戏风格。如果程序无法猜出正确答案,它将询问用于区分答案的问题,并将该问题存储在树中。它在程序开始时从文件系统中读取树,并在最后将其写回。
我在Haskell中的序列化代码遇到了很多问题。我收到错误“Prelude read:no parse”。这是怎么回事?这是我的代码:
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")
答案 0 :(得分:4)
read
并非旨在强有力地处理额外括号等内容。您的代码适用于我使用以下数据文件:
Question "Does it live in the water?"
(Question "Does it hop?" (Answer "frog") (Answer "fish"))
(Answer "cow")