使用标题以表格格式打印地图

时间:2014-08-24 19:07:17

标签: haskell

在Haskell中给出一个Integer Map(Map Int Int)我可以在使用print(myMap)时打印出这样的输出:

[(1,7),(2,24),(3,7)]

但是我需要它以表格格式显示这样的标题:

ID COUNT
1  7
2  24
3  7

是否有内置的Haskell可以在表格中显示地图,还是生成表格视图的方式? 谢谢,

1 个答案:

答案 0 :(得分:2)

hackage上的boxes库可用于打印相当可打印值的表格视图。

{-# LANGUAGE FlexibleInstances #-}

import qualified Text.PrettyPrint.Boxes as PB

class Pretty a where
  ppr :: a -> PB.Box

instance Pretty String where
  ppr = PB.text

instance Pretty Integer where
  ppr = PB.text . show

col :: (Pretty a, Pretty t) => (t, [a]) -> PB.Box
col (a, xs) = PB.vcat PB.left $ lab ++ vals
  where
    lab = [ppr a]
    vals = fmap ppr xs

ex1 :: String
ex1 = PB.render $ PB.hsep 1 PB.left $ fmap col cols
  where
    cols :: [(String, [Integer])]
    cols = [
        ("ID"    , [1,2,3]),
        ("COUNT" , [7,24,7])
      ]

main :: IO ()
main = putStrLn ex1

-- ID COUNT
-- 1  7
-- 2  24
-- 3  7