我已将(Matrix)数据类型定义为2D列表:
newtype Matrix a = M [[a]]
和Show
的实例,如下所示:
instance Show a => Show (Matrix a) where
show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
其行为如下:
> mat = M [[3,1,8],[6,3,0],[6,8,8]]
> mat
3 1 8
6 3 0
6 8 8
但是,我想处理打印列表的方式,因为默认行为看起来有点奇怪。我该如何指定?我尝试过这样的事情:
instance Show a => Show ([Matrix a]) where
show mat = case mat of
[M a] -> intercalate "\n" (map (unwords . map show) a) ++ "\n"
(m:ms) -> show m ++ "\n" ++ show ms
instance Show a => Show (Matrix a) where
show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
show (m:ms) = show m ++ "\n" ++ show ms
但我只是语法错误。我试过谷歌搜索问题,但我找不到任何东西(也许我使用了错误的关键词?)
提前致谢。
编辑:
所需的输入和输出:
mat1 = M [[1,2],[3,4]]
mat2 = M [[1,2],[3,4]]
> [mat1, mat2]
1 2
3 4,
1 2
3 4
答案 0 :(得分:2)
这正是showList
方法的用途:
instance Show a => Show (Matrix a) where
show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
showList (m:ms) = shows m . ("\n" ++) . showList ms
请注意,这不会处理空列表,因此您还需要
showList [] = id
(或者您希望它为空列表显示的任何内容。)