Problem 08

99 Haskell Problems

Problem 8

(**) Eliminate consecutive duplicates of list elements.

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.

Example:

* (compress '(a a a a b c c a a d e e e e))
(A B C A D E)

Example in Haskell:

> compress "aaaabccaadeeee"
"abcade"

Solution:

compress (x:ys@(y:_))
    | x == y = compress ys
    | otherwise = x : compress ys
compress ys = ys

Note: the expression ys@(y:_) define the following syntax

  • ys is a list define as (y:_)
  • y is the head of the list ys
  • _ is the tail of the list ys
Advertisements