Search code examples
exceptionhaskellsyntaxrecord

Haskell record syntax and read from file. String to record syntax. *** Exception: Prelude.read: no parse


I have the below Record Syntax.

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"]]

I would like to create an IO function that reads a books.txt file and converts it to type Database. I think it needs to be similar to my attempt below.

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

What is the correct format the books.txt file?

Below is my current books.txt content (same as bookDatabase).

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

*** Exception: Prelude.read: no parse


Solution

  • The derived Read instance for records can only read record syntax. It can't read a record that's in the format of a constructor applied to arguments in order. Try putting the following (which is the result of show bookDatabase) into books.txt.

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