How to implement Read instance for user defined type

Hi, I am trying to understand how to define instances for Read class for a user defined type. This is the sample code I wrote, but I am not able to get it correctly. So, let me know what's wrong with this program: module Mark where data Mark = Mark Int deriving (Show) instance Read Mark where readsPrec _ str = [(Mark x, t') | ("mark",t) <- reads str, (x,t') <- reads t When I run it in ghci: *Mark> reads "mark 5" :: [ (Mark,String)] ( I am intentionally using mark in lowercase) [] Why is the output coming out as [] as against expected output [(Mark 5, "")] ? -Anurag

Verma Anurag wrote:
module Mark where
data Mark = Mark Int deriving (Show)
instance Read Mark where readsPrec _ str = [(Mark x, t') | ("mark",t) <- reads str, (x,t') <- reads t
The problem with this instance is that reads expect Strings to be enclosed in double quotes: *Mark> read "mark" :: String "*** Exception: Prelude.read: no parse *Mark> read "\"mark\"" :: String "mark" Let's try this with your instance: *Mark> read "\"mark\" 4" :: Mark Mark 4 That works, but is probably not what you want. You can use the lex function to parse identifiers not enclosed in quotes:
instance Read Mark where readsPrec _ str = [(Mark x, t') | ("mark",t) <- lex str, (x,t') <- reads t
Now, it's working fine: *Mark> read "mark 4" :: Mark Mark 4 Tillmann
participants (2)
-
Tillmann Rendel
-
Verma Anurag-VNF673