Haskell 99 Problems - Solutions to 11 and 12


/ Published in: Haskell
Save to your folder(s)

problem 11, modified run-length encoding
========================================
If an element has no duplicates, mark it as such.

Example:

encodeModified "aaaabccaadeeee"

[Multiple 4 'a',Single 'b',Multiple 2 'c',
Multiple 2 'a',Single 'd',Multiple 4 'e']

problem 12, Decode a run-length encoded list.
=============================================
Given a run-length code list generated as specified in problem 11. Construct its uncompressed version.

Example:

decodeModified
[Multiple 4 'a',Single 'b',Multiple 2 'c',
Multiple 2 'a',Single 'd',Multiple 4 'e']

"aaaabccaadeeee"


Copy this code and paste it in your HTML
  1. data EncodedElement a = Multiple Int a | Single a
  2. deriving Show
  3.  
  4. encodeModified :: (Eq a) => [a] -> [EncodedElement a]
  5. encodeModified = map (\x -> if (length x > 1)
  6. then Multiple (length x) (head x)
  7. else Single (head x)) . group
  8.  
  9.  
  10. decodeModified :: [EncodedElement a] -> [a]
  11. decodeModified = concatMap decode
  12. where
  13. decode (Multiple n c) = replicate n c
  14. decode (Single c) = c : []

URL: http://www.haskell.org/haskellwiki/99_questions/11_to_20

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.