2012-12-04 59 views
1

我想打印一個矩陣。例如: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] 
       [4,5,6] 
       [7,8,9] -- this line is not showed on my instance Show 

如何顯示矩陣中的所有元素?謝謝。

+1

你知道'head'將列表的第一個元素,對不對?這就是爲什麼你的矩陣的其餘部分沒有被顯示。幸運的是,如果你不想要的話,不需要寫一個明確的遞歸顯示函數; Haskell有很多有用的組合器來爲你捕捉這些模式。例如,嘗試'show(Matr xs)=插入「\ n」(地圖顯示xs)'。 ('intercalate'是'Data.List'的一個有用的組合器。) – Fixnum

+0

我試過這個:show(Matr(x:xs))= show(x)++「\ n」++ show(Matr(xs) )。 但它有一個錯誤:程序錯誤:模式匹配失敗:v2897_v2908(Matr []) – tomss

+1

您需要爲遞歸包含一個基本情況;這意味着提供'show(Matr [])= ...'形式的子句;可能只是'show(Matr [])=「」' – Fixnum

回答

4

您必須遍歷所有元素

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 
+2

另外,請注意@Fixnum指出的'intercalate'函數(來自'Data.List'),'show(Matr d)= intercalate「\ n」。地圖顯示$ d'。 – huon