且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Haskell中的字符串中的任意位置将双精度空格转换为单精度空格

更新时间:2023-02-23 10:27:41

发生这种情况的原因是因为 y:xs xs 不会递归在字符串的其余部分.因此,您希望对字符串的其余部分执行该功能.

The reason this happens is because y:xs and xs will not recurse on te rest of the string. You thus want to perform the function on the rest of the string.

因此,您应该在 xs 上以形式调用 normaliseSpace .例如:

You thus should call normaliseSpace on xs as tail. For example:

normaliseSpace:: String -> String
normaliseSpace "" = ""
normaliseSpace (' ' : ' ' : xs) = ' ' : normaliseSpace xs
normalissSpace (x:xs) = x : normaliseSpace xs

请注意,您还需要为空字符串(列表)添加一个模式.因为否则最终递归将到达列表的末尾,并由于没有子句可以触发"而引发错误.

Note that you need to add a pattern for the empty string (list) as well. Since otherwise eventually the recursion will reach the end of the list, and thus raise an error because there is no clause that can "fire".

如果您想减少一系列空格(两个或更多 到一个),那么我们甚至需要通过 normalizeSpace传递'':xs ,例如

If you want to reduce a sequence of spaces (two or more to one), then we even need to pass ' ' : xs through the normalizeSpace, like @leftroundabout says:

normaliseSpace:: String -> String
normaliseSpace "" = ""
normaliseSpace (' ' : ' ' : xs) = normaliseSpace (' ':xs)
normalissSpace (x:xs) = x : normaliseSpace xs

我们可以在此处使用样式,例如

We can use an as-pattern here, like @JosephSible suggests:

normaliseSpace:: String -> String
normaliseSpace "" = ""
normaliseSpace (' ' : xs@(' ' : _)) = normaliseSpace xs
normalissSpace (x:xs) = x : normaliseSpace xs