Haskell如何删除字符串中多余的空格



试图创建一个函数,删除字符串(并将它们合并到一个单独的空间(

到目前为止,我已经能够去除两个空格,但不知道如何去除三个或更多。

"a b c d e"->"a b c d e"

formatSpace :: String -> String
formatSpace [] = []
formatSpace (' ':' ':xs) = ' ': formatSpace xs
formatSpace (x:xs)   = x: formatSpace xs

试着把所有的空格变成say"-",然后把所有这些变成一个空格。能够移动前导和尾随空白,但不能做这个

我会这样做:

formatSpace :: String -> String
formatSpace = foldr go ""
where
go x acc = x:if x == ' ' then dropWhile (' ' ==) acc else acc

这是最懒惰的,不会创建任何不必要的中间数据结构。

最新更新