如何打印列矩阵?

时间:2014-06-05 01:11:46

标签: haskell

我正在尝试在Haskell中打印出列矩阵的内容:

data Vector n e where
    Nil :: Vector Zero e
    (:>) :: e -> Vector n e -> Vector (Succ n) e

infixr :>

data Matrix r c e where
    ColMatrix :: Vector r e -> Matrix r One e
    (:|) :: Vector r e -> Matrix r c e -> Matrix r (Succ c) e

infixr :|

instance Show e => Show (Matrix r c e) where
    show (ColMatrix v) = -- ...
    show (v :| m)      = -- ...
但是,我不确定如何实现这一点。合乎逻辑的进展是

1 4 7
2 5 8
3 6 9

但打印到终端并不会使这一点变得特别容易。

如何为Show

实现ColMatrix的此实例

2 个答案:

答案 0 :(得分:1)

这是一个使用普通列表和列表库函数的解决方案。

toList :: Vector n e -> [e]
toList Nil = []
toList (a :> v) = a : toList v

instance Show e => Show (Matrix r c e) where
    show (ColMatrix v) = concat $ intersperse " "  (map show  (toList v))
    show (v :| m)      = show (ColMatrix v) ++ "\n" ++ show m

答案 1 :(得分:1)

你可能想要考虑像Brent Yorgey的boxes包这样的东西,我最近接手了它的维护。使用text将每个数字放在一个框中,使用//构建列,然后使用<+>将列放在一个矩阵中。然后render结果。您可以使用cols比较列的宽度,然后将它们粘贴在一起,这样您就可以根据需要将它们全部填充到相同的宽度。

请注意Show 非常适合打印。它适用于人类可读的序列化,类似Haskell格式。

相关问题