问题描述
我无法编写这个带有字符和字符列表的函数,然后消除列表中输入字符的最后一次出现。我可以用下面的函数取出第一次出现的输入字符:
I'm having trouble writing this function that takes a character and a list of characters, then eliminates the last occurrence of that input character in the list. I was able to take out the first occurrence of the input character with my function below:
fun :: Char -> String -> String
fun c (s:ss)
| s == c = ss
| otherwise = s : fun c ss
fun _ [] = []
帮助是我应该如何修改这个函数来取出输入字符的最后一次出现,而不是第一次。结果应该是类似于 fun'c'abcdccytrc
返回abcdccytr
。
What I need help on is how I should modify this function to take out the last occurrence of the input character, instead of the first. The result should be something like fun 'c' "abcdccytrc"
returning "abcdccytr"
.
推荐答案
正如Numeri所示,通过移除反转列表中的第一个匹配项来移除最后一个匹配项是一种方法:
As Numeri suggests, removing the last occurrence by removing the first occurrence in the reversed list is one way:
removeFirst :: Char -> String -> String
removeFirst _ [] = []
removeFirst c1 (c2:cs) = if c1 == c2 then cs else c2:removeFirst c1 cs
removeLast :: Char -> String -> String
removeLast c1 = reverse . removeFirst c1 . reverse
正如Will Ness所建议的那样,返回最后一次出现的字符串被删除,指示当前事件是否应该被移除,是另一个:
As Will Ness suggests, returning the string in which the last occurrence is removed, and a boolean to indicate whether the current occurrence should be removed or not, is another:
removeLast :: Char -> String -> String
removeLast c1 = snd . remLast
where
remLast :: String -> (Bool, String)
remLast [] = (False, [])
remLast (c2:cs) =
case remLast cs of
(True, cs') -> (True, c2:cs')
(False, cs') -> if c1 == c2 then (True, cs') else (False, c2:cs')
这篇关于Haskell函数取出输入字符的最后一个出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!