Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove repeating list elements using recursion and pattern matching in Haskell

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]
like image 787
Coding Elf Avatar asked May 11 '18 17:05

Coding Elf


1 Answers

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)
like image 143
ktzr Avatar answered Oct 20 '22 15:10

ktzr