1

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

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

我能够使用以下方法实现这一目标。

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

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

4

4 回答 4

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

不,但是看看你是否可以把 c​​oncatMap 写成一个 foldr ......

于 2009-05-12T01:36:27.020 回答
4

我看到'|'之间有一个额外的空格 和 word,所以你可以使用这个功能:

printfieldName x = unwords (map ((++) "|") x)  ++ "|"

小解释:

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

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

然后unwords将它们连接成一个字符串,单词之间有空格。++ "|"需要添加final|

于 2009-05-12T01:49:37.183 回答
4

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

printfieldName xs = "|" ++ unwords (intersperse "|\t" xs) ++ "|"
于 2009-05-12T02:15:17.033 回答
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 |
于 2010-02-23T22:00:45.527 回答