Exception: Non-exhaustive patterns in function

青春壹個敷衍的年華 提交于 2019-12-10 14:55:40

问题


Attempting to create a function that removes duplicates from a list, and replaces them with a single element. Keep getting an error message "Non-exhaustive patterns in function removeduplicate". I assume that means my pattern matching is missing a possible case? I think I've covered all the possibilities though. I'm very new to Haskell, so any help is greatly appreciated.

removeduplicate :: (Eq a) => [a] -> [a]
removeduplicate [] = []
removeduplicate (x:[]) = [x]
removeduplicate (x:z:[]) = if z == x then [x] else (x:z:[])
removeduplicate (x:y:[xs])
    | x == y = x:(removeduplicate [xs])
    | otherwise = x:y:(removeduplicate [xs])

回答1:


Your problem is in your final pattern. I assume it is meant to match all lists, but the way you have it, it is matching a list with one element, xs, in it.

This means the compiler is seeing a match for a 3 element list, but not for an arbitrary length list, which is why it is complaining.

To fix this, remove the box around xs.

removeduplicate (x:y:xs)
    | x == y = x:(removeduplicate xs)
    | otherwise = x:y:(removeduplicate xs)

Now xs is treated as a list, so you are matching lists with at least three items, rather than just three items.




回答2:


As Matt Bryant said, the particular compiler error stems from using [xs] instead of xs.

You actually have a redundant pattern in there, as well:

removeduplicate (x:z:[]) if z == x then [x] else (x:z:[])

This line can be removed, because a pattern of type x:y:[] is already handled by

removeduplicate (x:y:xs)
    | x == y = x:(removeduplicate xs)
    | otherwise = x:y:(removeduplicate xs)

Since xs can be the empty list and removeduplicate [] resolves into [].

Keep in mind, though, that the code you provided only removes up to 2 successive duplicate elements. With three successive duplicates, two identical elements will be inserted into the result, which is probably not what you want.

A more complete function could look something like this:

removeduplicate []     = []
removeduplicate (x:xs) = x:(removeduplicate $ dropWhile (== x) xs)


来源:https://stackoverflow.com/questions/17983936/exception-non-exhaustive-patterns-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!