Haskell 哈斯凯尔班级表演

Haskell 哈斯凯尔班级表演,haskell,Haskell,我想打印一个矩阵。例如: data Matrix = Matr [[Int]] instance Show Matrix where show(Matr (x:xs)) = show(x)++"\n"++show(head(xs)) Example of use: Matr [[1,2,3],[4,5,6],[7,8,9]] [1,2,3]

我想打印一个矩阵。例如:

       data Matrix = Matr [[Int]]

       instance Show Matrix where
                show(Matr (x:xs)) = show(x)++"\n"++show(head(xs))

       Example of use:

                Matr [[1,2,3],[4,5,6],[7,8,9]]
                [1,2,3]
                [4,5,6]
                [7,8,9] -- this line is not showed on my instance Show 

如何显示矩阵中的所有元素?谢谢。

您必须迭代所有元素

instance Show Matrix where
  show (Matr d) = print d
    where print [] = []
          print (x:xs) = show x ++ "\n" ++ print xs
另一种方式

instance Show Matrix where
  show (Matr d) = concatMap ((++"\n").show) d

必须迭代所有元素

instance Show Matrix where
  show (Matr d) = print d
    where print [] = []
          print (x:xs) = show x ++ "\n" ++ print xs
另一种方式

instance Show Matrix where
  show (Matr d) = concatMap ((++"\n").show) d

你知道
head
是列表的第一个元素,对吗?这就是为什么矩阵的其余部分没有显示出来。幸运的是,如果您不想,则无需编写显式递归show函数;Haskell有很多有用的组合器来为您捕获这些模式。例如,尝试
show(Matr-xs)=插入“\n”(map-show-xs)
。(
interlate
是来自
Data.List
的一个有用的组合词)我尝试了以下方法:show(Matr(x:xs))=show(x)+“\n”++show(Matr(xs))。但它有一个错误:程序错误:模式匹配失败:v2897_v2908(Matr[])您需要为递归包含一个基本情况;这里这意味着提供一个形式为show(Matr[])=…的子句;可能只是
show(Matr[])=”
你知道
head
取列表的第一个元素,对吗?这就是为什么矩阵的其余部分没有显示出来。幸运的是,如果您不想,则无需编写显式递归show函数;Haskell有很多有用的组合器来为您捕获这些模式。例如,尝试
show(Matr-xs)=插入“\n”(map-show-xs)
。(
interlate
是来自
Data.List
的一个有用的组合词)我尝试了以下方法:show(Matr(x:xs))=show(x)+“\n”++show(Matr(xs))。但它有一个错误:程序错误:模式匹配失败:v2897_v2908(Matr[])您需要为递归包含一个基本情况;这里这意味着提供一个形式为show(Matr[])=…的子句;可能只是
show(Matr[])=”
另外,请注意@Fixnum在上面指出的
interlate
函数(来自
Data.List
),
show(Matr d)=interlate“\n”。map show$d
。另外,请注意@Fixnum在上面指出的
interlate
函数(来自
Data.List
),
show(Matr d)=interlate“\n”。地图显示$d