使用show和Haskell中的列表列表

use*_*820 1 haskell types list

我在使用show打印由列表列表给出的矩阵行时遇到了一些麻烦.

我有这个:

data Matrix = Mat Int [[Bit]] 
    deriving Eq
Run Code Online (Sandbox Code Playgroud)

其中参数Int是平方矩阵的阶数,并且Bit是Int(0或1).我需要我的代码能够执行以下操作,Matrix作为以下实例Show:

Main> Mat 3 [[0,0,1],[1,0,1],[1,1,1]
[0,0,1]
[1,0,1]
[0,0,1]
Run Code Online (Sandbox Code Playgroud)

到目前为止我只有:

instance Show Matrix where
    show (Mat i (x:xs)) = (show x) ++ "\n"
Run Code Online (Sandbox Code Playgroud)

但这显然只返回第一个列表.你能帮我解决这个问题吗?提前致谢.

Dan*_*her 8

简单的方法是对show所有行,并将它们分别放在各自的行上:

instance Show Matrix where
    show (Mat _ rows) = unlines $ map show rows
Run Code Online (Sandbox Code Playgroud)

稍有的缺点是,它还在最后一行之后添加了换行符,以避免这种情况,您可以使用

instance Show Matrix where
    show (Mat _ rows) = intercalate "\n" $ map show rows
Run Code Online (Sandbox Code Playgroud)

(需要的进口Data.Listintercalate)