我是Haskell的新手,我正在写一个简单的AI决策系统来玩20个问题的游戏风格。如果程序无法猜出正确的答案,它会要求提供一个问题来区分答案,并将该问题存储在树中。它在程序开始时从文件系统中读取树,并在最后将其写回。调试Haskell阅读功能
我在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")
'Tree'不需要类型限定符 - 您可以轻松地用'Tree'替换所有'Tree a',而无需更改程序行为。 – 2010-11-16 18:29:20