# 99 Haskell Problems

## Problem 11

(*) Modified run-length encoding.

Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.

Example:

```* (encode-modified '(a a a a b c c a a d e e e e))
((4 A) B (2 C) (2 A) D (4 E))
```

Example in Haskell:

```P11> encodeModified "aaaabccaadeeee"
[Multiple 4 'a',Single 'b',Multiple 2 'c',
Multiple 2 'a',Single 'd',Multiple 4 'e']```

Solution:

```data CountElem a
= Single a
| Multiple Int a
deriving (Show, Eq)

encodeModified :: (Eq a) => [a] -> [CountElem a]
encodeModified [] = []
encodeModified x = convertWord (encode x)

convertWord :: (Eq a) => [(Int, a)] -> [CountElem a]
convertWord [] = []
convertWord ((n, s):xs)
| n == 1 = (Single s):(convertWord xs)
| otherwise = (Multiple n s):(convertWord xs)```

We reused the encode function from problem 10 to help convert it into a new type call CountElem.

Again we can simplify convertWord by using map in encodeModified.

```encodeModified x = map (convertWord) (encode x)
convertWord (n,s)
| n==1 = Single s
| otherwise = Multiple n s```
Advertisements