diff --git a/Haskell.org b/Haskell.org index 0d4a127..f07bcee 100644 --- a/Haskell.org +++ b/Haskell.org @@ -148,3 +148,50 @@ flatten = reverse . go [] go acc (Elem x) = x:acc go acc (List (x:xs)) = go (go acc x) (List xs) #+end_src +*** #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: + +#+begin_src haskell +,* (compress '(a a a a b c c a a d e e e e)) +(A B C A D E) +#+end_src + +Example in Haskell: + +#+begin_src haskell +λ> compress "aaaabccaadeeee" +"abcade" +#+end_src +**** Solution + +This is not great... + +#+begin_src haskell +compress xs = reverse $ go [] xs + where go acc [] = acc + go [] (x:xs) = go [x] xs + go [a] [x] + | a == x = [a] + | otherwise = [x,a] + go (a:as) [x] + | a == x = a:as + | otherwise = x:a:as + go [a] (x:xs) + | a == x = go [a] xs + | otherwise = go [x,a] xs + go (a:as) (x:xs) + | a == x = go (a:as) xs + | otherwise = go (x:a:as) xs +#+end_src + +Especially when one of the solutions is the following; + +#+begin_src haskell +import Data.List + +compress :: Eq a => [a] -> [a] +compress = map head . group +#+end_src