我正在尝试解决HackerRank上的一个简单问题,并在标题中收到错误。该问题要求接受一个字符串并通过删除相邻的字母对来减少它。所以“aabcdd”=> “bc”例如。这是我的代码:
main :: IO()
main = do
line <- getLine
putStrLn (reduce' line)
reduce' :: String -> String
reduce' [] = []
reduce' (x0:x1:xs)
| x1:xs == [] = [x0]
| x0 == x1 = reduce' xs
| otherwise = x0 : x1 : reduce' xs
我很困惑,因为我觉得我有边缘案例。我不想要问题的答案,我只是想知道为什么我得到错误。谢谢!
答案 0 :(得分:4)
您不匹配列表中只有一个元素的情况
reduce' :: String -> String
reduce' [] = []
reduce' [x] = [x]
reduce' (x0:x1:xs)
| x0 == x1 = reduce' xs
| otherwise = x0 : x1 : reduce' xs
此| x1:xs == [] = [x0]
是添加的模式匹配,因此无需检查警卫。