正如 Numeri 所建议的,通过删除反向列表中的第一个匹配项来删除最后一个匹配项是一种方法:
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 建议的那样,返回删除最后一次出现的字符串,以及指示是否应该删除当前出现的布尔值是另一种情况:
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')