I'm making a function that removes elements that occur two or more times in a row in a list. It replaces them with one occurrence. I'm using only recursion and pattern matching (no library list functions).
Examples of how the function should work:
unrepeat [True,True,True,True]
--> [True]
unrepeat [1,1,2,1,3,3,3]
--> [1,2,1,3]
What I have so far:
unrepeat :: Eq a => [a] -> [a]
unrepeat [] = []
unrepeat [x] = [x]
unrepeat (x:xs) = x : [ k | k <- unrepeat(xs), k /=x]
I believe your implementation will remove all duplicates in the list, it looks like you want to only keep an element in the list if it is not equal to the next element.
Give this a try:
unrepeat :: Eq a => [a] -> [a]
unrepeat [] = []
unrepeat [x] = [x]
unrepeat (x1:x2:xs) = if x1 == x2 then unrepeat(x2:xs) else x1:unrepeat(x2:xs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With