# 99 questions/Solutions/10

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

m (Linked to MR) |
(Added a solution that makes the usage of foldr) |
||

Line 25: | Line 25: | ||

encode :: Eq a => [a] -> [(Int, a)] |
encode :: Eq a => [a] -> [(Int, a)] |
||

encode xs = map (length &&& head) $ group xs |
encode xs = map (length &&& head) $ group xs |
||

+ | </haskell> |
||

+ | |||

+ | Or with the help of foldr: |
||

+ | |||

+ | <haskell> |
||

+ | encode xs = (enc . pack) xs |
||

+ | where enc = foldr (\x acc -> (length x, head x) : acc) [] |
||

</haskell> |
</haskell> |

## Revision as of 14:46, 16 August 2010

(*) Run-length encoding of a list.

Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.

encode xs = map (\x -> (length x,head x)) (group xs)

which can also be expressed as a list comprehension:

[(length x, head x) | x <- group xs]

Or writing it Pointfree (Note that the type signature is essential here to avoid hitting the Monomorphism Restriction):

encode :: Eq a => [a] -> [(Int, a)] encode = map (\x -> (length x, head x)) . group

Or (ab)using the "&&&" arrow operator for tuples:

encode :: Eq a => [a] -> [(Int, a)] encode xs = map (length &&& head) $ group xs

Or with the help of foldr:

encode xs = (enc . pack) xs where enc = foldr (\x acc -> (length x, head x) : acc) []