Haskell试图使类Matrix显示实例

时间:2016-03-20 18:50:26

标签: haskell

我是哈斯克尔的初学者,请告诉我我做错了什么。

    newtype (Matrix a) = Matr [[a]]
    instance Show (Matrix a) where
        show (Matr d) = print d
            where print [] = []
                print (x:xs) = show x ++ "\n" ++ print xs

    No instance for (Show a) arising from a use of `print'
    Possible fix:
    add (Show a) to the context of the instance declaration

2 个答案:

答案 0 :(得分:3)

错误消息显示"您需要一个Show实例作为矩阵的元素类型"。

此处调用print是错误的函数 - show在java等语言中等同于toString - 而print是一个IO操作,它放置一个{ {1}}对于stdout,您使用的是已经有意义的名称。

String

现在这个newtype Matrix a = Matr [[a]] instance Show a => Show (Matrix a) where show (Matr xx) = showlines xx where showlines [] = "" showlines (x:xs) = showelems x ++ "\n" ++ showlines xs showelems [] = "" showelems (x:xs) = show x ++ " " ++ showelems xs / showline模式已经是函数showelemsunlines的常见模式,但元素必须已经是字符串

unwords

或有点terser

    show (Matr xx) = let strs = map (map show) xx
                     in unlines $ map unwords xx

以下是 show (Matr xx) = unlines $ map (unwords . map show) xx / unlines

的一些示例用法
unwords

@ lisyarus'答案显示了场景背后发生的更多事情 - 但请注意,该节目功能的输出与我的不同。

$ > ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> putStrLn $ unlines ["a","b"]
a
b

Prelude> putStrLn $ unlines $ map unwords [["a","b"],["c","d"]]
a b
c d

Prelude> putStrLn $ unlines $ map (unwords . map show ) [[1,2],[3,4]]
1 2
3 4

答案 1 :(得分:2)

print (x:xs) = show x ++ "\n" ++ print xs

此处x的类型为[a]。实例Show [a]需要Show a的实例。换句话说,您必须告诉如何展示a才能展示[a]

在实例声明中添加对Show a的依赖:

instance (Show a) => Show (Matrix a) where
    ...

顺便说一句,您的代码可以使用标准库编写,如下所示:

show (Matr d) = concat . intersperse "\n" . map show $ d

注意:您需要在import Data.List函数的矩阵模块中intersperse