如何在Haskell中使用'unwords'打印字符串列表?

时间:2009-05-12 01:24:13

标签: list haskell pretty-print

我想打印如下所示的字符串列表。

|Name|Country|Age|
------------------
|1   |USA    |20 |
|2   |UK     |19 |

我能够通过以下方式实现这一目标。

printfieldName :: [String] -> String
printfieldName [] = []
printfieldName (x:xs)  = "|" ++ x ++ "\t" ++ printfieldName (xs)

是否可以使用内置函数'unwords'来实现这一点。我能够使用'unwords'打印它,但无法在单词之间放置|

4 个答案:

答案 0 :(得分:4)

首先,我会这样写:

printfieldName []     = []
printfieldName (x:xs) = "|" ++ x ++ "\t" ++ printfieldName xs

嗯,实际上,不,就像这样:

concatMap (\x -> '|' : x ++ "\t")

好吧,也许更像是:

concatMap (printf "|%s\t")

行。它可以用'unwords'来完成吗?

-- | 'unwords' is an inverse operation to 'words'.
-- It joins words with separating spaces.
unwords                 :: [String] -> String
unwords []              =  ""
unwords ws              =  foldr1 (\w s -> w ++ ' ':s) ws

没有。但看看你是否可以将concatMap编写为折叠器......

答案 1 :(得分:4)

我看到'|'之间还有一个空格和单词,所以你可以使用这个功能:

printfieldName x = unwords (map ((++) "|") x)  ++ "|"
小解释:

(++) "|" - creates a function which take prefixes each word with "|", so
(++) "|" "test" -> "|test" 

然后,map将此函数应用于将其转换为["|1", "|USA", "|20", ... ]的单词列表

然后unwords将它们连接成一个字符串之间的空格。添加最终++ "|"

需要|

答案 2 :(得分:4)

Data.List有一个名为intersperse的函数。也许你可以使用它。

printfieldName xs = "|" ++ unwords (intersperse "|\t" xs) ++ "|"

答案 3 :(得分:1)

也许你提出的问题有点过分了,但是:

formatTable :: [String] -> [[String]] -> String
formatTable header rows =
    formatRow header ++ dashRow ++ concatMap formatRow rows

    where formatRow cells = bracket '|' (spread cells)
          dashRow         = bracket '+' (map (\n -> replicate n '-') widths)
          bracket c cells = concatMap (c:) cells ++ (c:"\n")

          spread cells    = zipWith pad widths cells
          pad n s         = take n (s ++ repeat ' ')

          widths = foldr maxLengths (repeat 0) (header : rows)
          maxLengths = zipWith (\c l -> max (length c) l)

然后,例如:

> let h = words "Name Country Age"
> let rows = map words ["1 USA 20", "2 UK 19"]
> h
["Name","Country","Age"]
> rows
[["1","USA","20"],["2","UK","19"]]
> putStr $ formatTable h rows
|Name|Country|Age|
+----+-------+---+
|1   |USA    |20 |
|2   |UK     |19 |