问题描述
我正在编写一个将char作为输入的递归函数,并从输出的字符串中删除char。
例如:输入:abbacysa |输出:bbcys
我是Haskell的初学者,所以请尝试在实践中绕过递归。
我首先创建一个带有空列表的函数 然后,我选择列表中的元素并开始条件保护。 我考虑使用drop,但是我认为也许有更好的方法?
removeChar [] = []
removeChar (x:xs)
| x `elem` "a" = removeChar drop "a"
解决方法
您从递归基础开始:
removeChar [] = []
如果字符串不为空,则有两个可能的选择:
- 它从
a
开始,然后您要跳过。因此结果就是字符串的其余部分,没有字母'a'
。
removeChar ('a':xs) = removeChar xs
- 没有,那么您想保留它。因此结果是字母加上字符串的其余部分,而没有字母
'a'
。
removeChar (x:xs) = x: removeChar xs
,
这是一个解决方案,其中您输入了字符串和要从字符串中删除的字符。
递归:
removeChar :: String -> Char -> String
removeChar [] _ = []
removeChar (x:xs) n = if (x == n) then removeChar xs n
else x : removeChar xs n
首先,我们检查字符串(x:xs)中的char“ x”等于char“ n”,如果是,则删除字符,否则继续循环遍历字符串。
Input: removeChar "abba baby" 'b'
Output: "aa ay"