Haskell - 我如何去除尾随空格

Haskell - how do I strip trailing spaces

我想将 [1,2,3] 转换为“1 2 3”。此刻我得到“1 2 3”。 我使用

导入 strip 函数
import Data.Text (strip)

我的代码如下所示:

ar2str ar = (concatMap (\x -> (show x)++" " ) ar)

如何修改 ar2str 以使其与 strip 一起使用?

找到了

http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Haskell

Rosetta 代码来拯救:-)

您可能想使用 Data.Text.unwords 而不是所有这些。或者,如果您使用 String 而不是 TextData.List.unwords.

如果处理给定的输入字符串,则剥离尾随 space 是有意义的。如果要生成字符串,最好不要首先附加 space。特别是考虑到 Haskell 列表的性质,从末尾删除元素等于重建列表。

这是实现预期效果的一种方法:

ar2str :: Show a => String -> [a] -> String
ar2str _ [x] = show x
ar2str sep (x:x':xs) = show x ++ sep ++ ar2str sep (x':xs)