exception - Haskell 记录语法并从文件中读取。记录语法的字符串。 *** 异常 : Prelude. 读取:无解析

标签 exception haskell syntax record

我有以下记录语法。

type Title = String
type Author = String
type Year = Int
type Fan = String


data Book = Book { bookTitle :: Title
                 , bookAuthor:: Author
                 , bookYear  :: Year
                 , bookFans  :: [Fan]
                 }
                 deriving (Show, Read)


type Database = [Book]

bookDatabase :: Database 
bookDatabase = [Book "Harry Potter" "JK Rowling" 1997 ["Sarah","Dave"]]

我想创建一个读取 books.txt 文件并将其转换为数据库类型的 IO 函数。我认为它需要类似于我下面的尝试。

main :: IO()
main = do fileContent <- readFile "books.txt";
          let database = (read fileContent :: Database)

books.txt 文件的正确格式是什么?

下面是我当前的 books.txt 内容(与 bookDatabase 相同)。

[Book "Harry Potter" "JK Rowling" 1997 ["Sarah","Dave"]]

*** Exception: Prelude.read: no parse

最佳答案

记录的派生Read 实例只能读取记录语法。它无法读取按顺序应用于参数的构造函数格式的记录。尝试将以下内容(show bookDatabase 的结果)放入 books.txt

[Book {bookTitle = "Harry Potter", bookAuthor = "JK Rowling", bookYear = 1997, bookFans = ["Sarah","Dave"]}]

关于exception - Haskell 记录语法并从文件中读取。记录语法的字符串。 *** 异常 : Prelude. 读取:无解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813161/

相关文章:

c# - 数据读取器 MYSQL 中没有当前查询

c++ - C++中的语义差异,定义常量数据实例

Python 处理特定的错误代码?

java - 将异常抛出回调用方法

haskell - 安装 zlib 时 ghc.exe 无法执行 ld.exe

parsing - 语言设计 : How does evaluation of parsed expressions work in Haskell?

c# - 如何以编程方式自动将我的 c# 应用程序问题添加到 Github

ios - 快速捕获无效用户输入的异常

haskell - 如何实现 mapAccumM?

java - 当我不知道有多少项目时如何初始化数组