Search code examples
haskellcompressionrun-length-encoding

Compressing by counting repetitive elements (Haskell)


I'm looking for a straight-forward combination of standard higher-order functions to compress a list by counting repetitive elements. For example the result for

"abbccccb"

would be :

 [(1, 'a'), (2, 'b'), (4, 'c'), (1, 'b')] 

another example, the result for

(sort "abrakadabra") 

would be:

[(5, 'a'), (2, 'b'), (1, 'd'), (1, 'k'), (2, 'r')]

Solution

  • I wrote a code that only makes use of elementary functions.

    f :: Eq a => [a] -> [(Int, a)]
    f [] = []
    f (x:xs) = (1 + length (takeWhile (==x) xs), x) : f (dropWhile (==x) xs)
    

    I hope this will help!.