list - 在 Haskell 中格式化列表输出?

标签 list haskell types pretty-print

我在尝试在 Haskell 中格式化我自己类型的列表的输出时遇到问题。

我想要这样的东西:

Make  | Model | Years(this is a list)    <- this would be the headers if you like
-------------------
Item1 | Item1 | Item1s,Item1s           
Item2 | Item2 | Item2s,Items2,Items2

^
这将是从我的 String String [Int] 类型加载的数据。

我将如何在 Haskell 中执行此操作?

最佳答案

通常,我们使用“ pretty-print ”库来进行漂亮的格式化输出。您应该知道的标准是Text.PrettyPrint .给定一个数据类型,您可以遍历该类型,构建一个格式良好的文档。

一个例子:

import Text.PrettyPrint
import Data.List

-- a type for records
data T = T { make  :: String
           , model :: String
           , years :: [Int] }
    deriving Show

-- test data
test =
    [ T "foo" "avenger" [1990, 1992]
    , T "bar" "eagle"   [1980, 1982]
    ]

-- print lists of records: a header, then each row
draw :: [T] -> Doc
draw xs =
    text "Make\t|\tModel\t|\tYear"
   $+$
    vcat (map row xs)
 where
    -- print a row
    row t = foldl1 (<|>) [ text (make t)
                         , text (model t)
                         , foldl1 (<^>) (map int (years t))
                         ]

-- helpers
x <|> y = x <> text "\t|\t" <> y
x <^> y = x <> text "," <+> y

测试:
main = putStrLn (render (draw test))

结果是:
Make    |   Model   |   Year
foo     |   avenger |   1990, 1992
bar     |   eagle   |   1980, 1982

快速编写 pretty-print 的能力是一项非常有用的技能。

关于list - 在 Haskell 中格式化列表输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5929377/

相关文章:

python - 将 Python 列表转换为 Pandas 系列

haskell - 从 lambda 项到组合项的转换

haskell - 在 Haskell 中读取文本文件并分别处理该文件的每一行

haskell - 使用 DataKinds 扩展时如何导出类型构造函数?

python - 从 float 列表中删除所有出现的整数

c# - 在 javascript 中循环 C# 列表

c# - 将一系列项目添加到列表的开头?

haskell - 如何在 lambda 演算中进行编码

另一个引用的不同合并程序集中的 C# 相同类型和命名空间

C类型无法被正确识别