纠正值 a 的读取
首先,不要费心删除空格,这一切都可以很好地处理reads
:
readsMatrix :: (Read a) => ReadS (Value a)
readsMatrix ('-':s) = [(Nul, dropWhile (==' ') s)]
readsMatrix s = [(Val x,rest)| (x,rest) <- reads s]
您的读取实例现在适合单个值:
*Main> read "4" :: Value Int
Value4
*Main> read "-" :: Value Int
Nothing 0
更正 [值 a] 的读取
但是您想要读取由空格分隔的列表,因此由于这是非标准行为,您需要编写一个自定义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]
但不幸的是,
*Main> read "- 4 2 \n- 5 4" :: [Value Int]
[Nothing 0,Value4,Value2,Nothing 0,Value5,Value4]
更糟糕的是,
*Main> read "- 4 2 \n- 5 4" :: [[Value Int]]
*** Exception: Prelude.read: no parse
读取矩阵
我认为没有直接的方法来解决这个问题,因为没有readListOfLists
in the Read
类,那么为什么不创建一个独立的函数
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]]
表演不是我会选择的
我认为你的Show
实例为Value
有点误导(Nul
上面没有零,Val
没有写Value
)。要么写
data Value a = Nul | Val a deriving Show
使其看起来像原来的样子或定义它以匹配Read
实例
instance Show a => Show (Value a) where
show Nul = "-"
show (Val a) = show a