也许你问的有点过头了,但是:
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 |