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

芝麻糊 阅读:141 2025-02-15 21:57:57 评论:0

我有以下记录语法。

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
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号