簡體   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