# Remove consecutive duplicates from a list in Haskell

Suppose a given list of integers has some consecutive duplicate entries and it is required to remove those duplicates and to keep just one entry of that integer. This can be done in Haskell programming language using foldr or foldl functions. It can also be done without using any fold functions. Here is the code for the same.

Without fold function

remdups :: [Int] -> [Int]
remdups [] = []
remdups [x] = [x]
remdups (x1:x2:xs)
| x1==x2 = remdups (x2:xs)
| otherwise = x1:remdups (x2:xs)

With foldr function

fnr :: (Eq a) => a -> [a] -> [a]
fnr x [] = [x]
fnr x xs
| x == head xs = xs
| otherwise = x:xs

remdups1 :: (Eq a) => [a] -> [a]
remdups1 [] = []
remdups1 ys = foldr fnr [] ys

With foldl function

fnl :: (Eq a) => [a] -> a -> [a]
fnl [] x = [x]
fnl xs x
| last xs == x = xs
| otherwise = xs ++ [x]

remdups2 :: (Eq a) => [a] -> [a]
remdups2 [] = []
remdups2 ys = foldl fnl [] ys

Output of the above codes will look like this..

*Main> remdups [1,2,2,1,3,3,4,1,2,2]
[1,2,1,3,4,1,2]
*Main> remdups1 [1,2,2,1,3,3,4,1,2,2]
[1,2,1,3,4,1,2]
*Main> remdups2 [1,2,2,1,3,3,4,1,2,2]
[1,2,1,3,4,1,2]

## Similar Posts

This site uses Akismet to reduce spam. Learn how your comment data is processed.