简体   繁体   English

调试Haskell读取功能

[英]Debugging Haskell read function

I'm new to Haskell and I'm writing a simple AI decision system to play a 20 questions style of game. 我是Haskell的新手,我正在编写一个简单的AI决策系统,以玩20个问题的游戏风格。 If the program is unable to guess the correct answer, it will ask for a question to use to distinguish the answer and it will store that question in a tree. 如果程序无法猜出正确的答案,它将要求使用一个问题来区分答案,并将该问题存储在树中。 It reads the tree in from the file system at the start of the program and writes it back out at the end. 它在程序开始时从文件系统中读取树,并在结束时将其写回。

I'm having a lot of problems with the serialization code in Haskell. 我在Haskell中的序列化代码有很多问题。 I'm getting the error "Prelude read: no parse". 我收到错误消息“ Prelude read:no parse”。 What's going on? 这是怎么回事? Here's my code: 这是我的代码:

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"

And here's the data file I'm using: 这是我正在使用的数据文件:

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

read is not intended to handle things like extra parentheses robustly. read不能强健地处理多余的括号之类的内容。 Your code works for me with the following data file: 您的代码对我适用于以下数据文件:

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