parsing - 调试Haskell读取函数

标签 parsing haskell

我是 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/

相关文章:

Haskell 预购遍历树列表

haskell - 如何在 ADT 或记录语法上使用 Monadic 绑定(bind)运算符

haskell - 作家 Monad 嵌套两次

java - 在 URL 处的 JSON 文件中查找某些字段

string - 如何在 Bash 脚本中从一系列 <string>_# 文件名中选择最大的数字

parsing - 以功能纯方式生成不可变的具体语法树的适当数据结构或算法是什么?

database - Haskell 中的电影数据库

algorithm - Haskell:展平二叉树

java - ElasticSearch - 无法识别的字符转义

c# - 获取模式之后没有类或 ID 的文本