Thanks to this excellent tutorial, I know how to read a string (in this case read from a file at people.txt directly into a type synonym:
type Person = [Int]
like this:
people_text <- readFile "people.txt"
let people :: [Person]
people = read people_text
What I want to do is use a datatype (instead of a type synonym).
Any pointers on what I am missing here? I thought I would be able to read string-data directly into a Person – defined like this (credit to learnyouahaskell.com)
data Person = Person String String Int Float String String deriving (Show)
When I try the obvious
txt <- readFile "t.txt" (this works OK)
with t.txt containing
"Buddy" "Finklestein" 43 184.2 "526-2928" "Chocolate"
I get this error:
No instance for
(Read Person)
First of all, you need to derive
Readfor your type.You can think of
readandshowas being opposites, and a sort of poor man’s serialization.showlets you convert toString,readconverts fromString, and in most cases theStringproduced should also be valid Haskell code that, when compiled, produces the same value thatreadgives you.On that note, the contents of your file aren’t going to work, because that’s not the format used by the default implementations of
readandshow, i.e. the implementations you get by puttingReadandShowin thederivingclause.For example, given this:
Then in GHCi, we get:
The quotes are escaped because that’s a
Stringvalue. In the file, it would look like this:Which you’ll note is the same as the original definition in the source file.