# Writing a Haskell code that compress the list

Hello. I am learning Haskell and I am currently writning Haskell code that (description blow)
Write a function that eliminates consecutive duplicates of list elements.

compress :: Eq a => [a] → [a]

If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.

For example:

compress [2,2,2,1,2,2,3,3,3]
[2,1,2,3]

Then my code is
remdups :: Eq a => [a] → [a]
remdups [] = []
remdups [x] = [x]
remdups (x1:x2:xs)
| x1==x2 = remdups (x2:xs)
| otherwise = x1:remdups (x2:xs)

main = putStrLn(show remdups[2,2,2,1,2,2,3,3,3])

I visited some websites that explain simmilar problem and I tryied to use some code from the websites, but did not work.

Could anyone tell and teach me what is wrong with mi code and fix my code?

Let’s try using some code fences around your example e.g:

```~~~haskell
remdups :: Eq a => [a] → [a]
remdups [] = []
remdups [x] = [x]
remdups (x1:x2:xs)
| x1==x2 = remdups (x2:xs)
| otherwise = x1:remdups (x2:xs)

main = putStrLn(show remdups[2,2,2,1,2,2,3,3,3])
~~~
```

After being rendered in Discourse:

``````remdups :: Eq a => [a] → [a]
remdups [] = []
remdups [x] = [x]
remdups (x1:x2:xs)
| x1==x2 = remdups (x2:xs)
| otherwise = x1:remdups (x2:xs)

main = putStrLn(show remdups[2,2,2,1,2,2,3,3,3])
``````

``````remdups :: Eq a => [a] → [a]
remdups []  = []
remdups [x] = [x]
remdups (x1:x2:xs)
| x1 == x2  = remdups (x2:xs)
| otherwise = x1 : remdups (x2:xs)

main = putStrLn (show remdups [2,2,2,1,2,2,3,3,3])
``````

That’s odd:

```#  ghci
GHCi, version 9.0.1: https://www.haskell.org/ghc/  :? for help
ghci> :i show
type Show :: * -> Constraint
class Show a where
...
show :: a -> String
...
-- Defined in ‘GHC.Show’
ghci>
```

`show` only requires one argument:

` show :: a -> String`

why is it being applied to two?

`... (show remdups [2,2,2,1,2,2,3,3,3]) ...`

(Hint: try using the `(\$)` operator…)

You could use `group` and `head` to achieve this:

``````import Data.List

main = do
let lst = [2,2,2,1,2,2,3,3,3]
let grp = group lst

print \$ map (head) grp   -- [2,1,2,3]
``````

The function `group` groups the data into lists, thus:

``````  lst = [2,2,2,1,2,2,3,3,3]
group lst     -- [[2,2,2],[1],[2,2],[3,3,3]]``````
1 Like