在Haskell中的字符串中的任意位置将双精度空格转换为单精度空格 [英] Converts a double space into single one anywhere in a String in Haskell

查看:53
本文介绍了在Haskell中的字符串中的任意位置将双精度空格转换为单精度空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试完成一个转换功能将String中的双倍空格转换为Haskell中的单个空格.

I've been trying to complete a function that converts double space in a String into a single space in Haskell.

normaliseSpace:: String -> String
normaliseSpace (x:y:xs)= if x==' ' && y==' ' then y:xs
else xs

我的代码的问题是仅在字符串的开头转换双精度空格.我想它与模式匹配有关,但是由于我对Haskell完全陌生,所以我真的不知道该怎么做.任何帮助将不胜感激!

The problem with my code is that only converts double spaces in the beginning of a String. I suppose it has something to do with pattern matching, but as I am completely new to Haskell I really don't have an idea how to do it. Any help will be appreciated!

推荐答案

发生这种情况的原因是因为 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

这篇关于在Haskell中的字符串中的任意位置将双精度空格转换为单精度空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆