【发布时间】:2017-08-27 08:50:55
【问题描述】:
我已将(矩阵)数据类型定义为二维列表:
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
【问题讨论】:
-
你展示了你已经在工作的输入和输出。您能否添加一个示例输入和您遇到问题的所需输出?
-
这可能会有所帮助!已编辑。
-
我不确定这是否是个好主意。
Show通常用于生成单行数据表示,通常为此使用 Haskell 语法。使用这样的多行文本会奇怪地与所有标准容器(如数组、地图、集合等)一起使用。(列表[]是特殊的并且可以自定义,无论如何。)我会考虑使用自定义的漂亮打印例程representatrix位于Show类之外。
标签: string list haskell instance