I want to implement an instance of read that enables me to read a string (ex: "- - 8 - 3 -") and construct a list containing those values.
data Value a = Nul | Val a
showsValue :: (Show a) => Value a -> ShowS
showsValue (Val x) = ("Value" ++) . shows x
showsValue (Nul) = ("Nothing 0" ++)
instance Show a => Show (Value a) where
showsPrec _ x = showsValue x
instance Read a => Read (Value a) where
readsPrec _ m = readsMatrix m
readsMatrix :: (Read a) => ReadS (Value a)
readsMatrix ('-':s) = [(Nul, rest) | (' ',rest) <- reads s]
readsMatrix s = [(Val x,rest)| (x,' ':rest) <- reads s]
After performing this test:
read "- 8 - - 3" :: Value Int
I get the error *** Exception: Prelude.read: no parse
What am I doing wrong here?
update
readsMatrix ('-':s) = [(Nul, dropWhile isSpace s)]
readsMatrix s = [(Val x, dropWhile isSpace rest) | (x,rest) <- reads s]
First, don't bother removing spaces, that's all handled fine by reads:
readsMatrix :: (Read a) => ReadS (Value a)
readsMatrix ('-':s) = [(Nul, dropWhile (==' ') s)]
readsMatrix s = [(Val x,rest)| (x,rest) <- reads s]
Your read instance is now fine for single Values:
*Main> read "4" :: Value Int
Value4
*Main> read "-" :: Value Int
Nothing 0
But you want to read lists as separated by spaces, so since that's non-standard behaviour, you'll need to write a custom readList :: :: ReadS [Value a]
instance Read a => Read (Value a) where
readsPrec _ m = readsMatrix m
readList s = [(map read.words $ s,"")]
So now
*Main> read "- 4 2 - 5" :: [Value Int]
[Nothing 0,Value4,Value2,Nothing 0,Value5]
but unfortunately,
*Main> read "- 4 2 \n- 5 4" :: [Value Int]
[Nothing 0,Value4,Value2,Nothing 0,Value5,Value4]
and even worse,
*Main> read "- 4 2 \n- 5 4" :: [[Value Int]]
*** Exception: Prelude.read: no parse
There's no straightforward way round this that I can see, because there's no readListOfLists in the Read class, so why not make a standalone function
matrix :: Read a => String -> [[Value a]]
matrix = map read.lines
so that
*Main> matrix "3 4 -\n3 - 6\n4 5 -" :: [[Value Int]]
[[Value3,Value4,Nothing 0],[Value3,Nothing 0,Value6],[Value4,Value5,Nothing 0]]
I think your Show instance for Value is a little misleading (Nul doesn't have a zero on it, Val isn't written Value). Either write
data Value a = Nul | Val a deriving Show
so that it looks as it is or define it to match the Read instance
instance Show a => Show (Value a) where
show Nul = "-"
show (Val a) = show a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With