2017-04-02 53 views
1

我已经定义了一个(矩阵)数据类型,作为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 

但我只是语法错误。我尝试使用Google搜索这个问题,但我找不到任何东西(也许我使用了错误的关键字?)

在此先感谢。

编辑:

期望中的输入和输出:

mat1 = M [[1,2],[3,4]] 
mat2 = M [[1,2],[3,4]] 
> [mat1, mat2] 
1 2 
3 4, 
1 2 
3 4 
+0

你显示了你已经有工作的输入和输出。你可以添加一个示例输入和你遇到麻烦的所需输出吗? – Libby

+0

这可能会有帮助!编辑。 – user3668541

+1

我不确定这是否是一个好主意。 'Show'通常意味着产生单行数据表示,通常为此使用Haskell语法。使用像这样的多行文本将与所有标准容器(如数组,地图,集合等)发生奇怪的结合(列表'[]'是例外的,并且可以自定义)。我会考虑使用自定义漂亮打印常规'代表性',它位于'Show'类之外。 – chi

回答

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 

(或任何你想让它显示空列表)