繁体   English   中英

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

[英]How to print a list of strings using 'unwords' in Haskell?

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

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

我可以使用以下方法实现此目的。

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

是否可以使用内置函数“ unwords”实现此目的。 我可以使用'unwords'打印它,但是无法放置| 字之间。

首先,我会这样写:

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

好吧,实际上,不,像这样:

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

好吧,也许更像是:

concatMap (printf "|%s\t")

好。 那么可以将其作为“单词”吗?

-- | '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编写为文件夹...

我看到“ |”之间还有一个空格 和单词,因此您可以使用以下功能:

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

小解释:

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

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

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

Data.List具有称为散布的功能。 也许您可以使用它。

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

也许比您的要求略高一点,但是:

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 |

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM