Problem 11

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.


* (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']


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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s