簡體   English   中英

調試Haskell讀取功能

[英]Debugging Haskell read function

我是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")

read不能強健地處理多余的括號之類的內容。 您的代碼對我適用於以下數據文件:

Question "Does it live in the water?"
        (Question "Does it hop?" (Answer "frog") (Answer "fish"))
        (Answer "cow")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM