Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 自定义数据类型的显示列表的实例_String_List_Haskell_Instance - Fatal编程技术网

String 自定义数据类型的显示列表的实例

String 自定义数据类型的显示列表的实例,string,list,haskell,instance,String,List,Haskell,Instance,我已将(矩阵)数据类型定义为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

我已将(矩阵)数据类型定义为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
这正是该方法的目的:

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

(或为空列表显示的任何内容。)

您显示了已经在工作的输入和输出。您能添加一个示例输入和您遇到问题的所需输出吗?这可能会有所帮助!编辑。我不确定这是否是个好主意<代码>显示通常用于生成单行数据表示,通常使用Haskell语法。使用这样的多行文本将对所有标准容器(如数组、映射、集合等)进行奇怪的操作(列表<代码> [] /代码>是例外的,并且可以被定制,无论如何,我会考虑使用自定义的漂亮打印例程<代码>代表符< /代码>,它位于<代码>显示< /代码>类之外。