我有以下记录语法。
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/