Exception: non-exhaustive patterns in a function

Trying to create a function that removes duplicates from a list and replaces them with a single element. Continue to receive the "Non-exhaustive templates in removeduplicate function" error message. I assume this means that there is no possible case in my template? I think that I have covered all the possibilities. I am 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]) 
+4
source share
2 answers

Your problem is your final outline. I assume that it is designed to fit all lists, but as it is, it maps the list to one xs element in it.

This means that the compiler sees a match for a list of 3 elements, but not for an arbitrary list of lengths, so it complains.

To fix this, uncheck xs .

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

Now xs treated as a list, so you map lists with at least three elements, not just three elements.

+10
source

As Matt Bryant said, a specific compiler error involves using [xs] instead of xs .

You actually have a redundant pattern:

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

This line may be deleted because a pattern of type x:y:[] already being processed

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

Since xs can be an empty list, and removeduplicate [] allowed in [] .

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

A more complete function might look something like this:

 removeduplicate [] = [] removeduplicate (x:xs) = x:(removeduplicate $ dropWhile (== x) xs) 
+5
source

Source: https://habr.com/ru/post/1494614/


All Articles