I've been working on these solutions to the Haskell 99 questions, encoding and decoding series for a while now, so I figured I ought to present them to see how I screwed up the implementation.
Problems:
Encoding: Write a function which encodes a series of characters using run-length encoding and an algebraic data type such that the sequence
"aaaabccaadeeee"
outputs:[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']
Decoding: Write a function which decodes a series of algebraic data types representing run-length encoding as a series of characters such that the sequence
[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']
outputs
"aaaabccaadeeee"
.
Here is the code I used for the problems:
import Data.List
main = do
print $ decode (encode "Mississippi")
data Encoding = Multiple Int Char | Single Char deriving (Show)
encode :: [Char] -> [Encoding]
encode chars= map toEncoding ( (countChars . group) chars)
where
countChars :: [String] -> [(Int, Char)]
countChars strings = map countCharsHelper strings
countCharsHelper :: String -> (Int, Char)
countCharsHelper chars = (length chars, head chars)
toEncoding :: (Int, Char) -> Encoding
toEncoding (1, a) = Single a
toEncoding (num, a) = Multiple num a
decode :: [Encoding] -> [Char]
decode encodings = foldl (++) "" (map replicateChars (map fromEncoding encodings))
where
fromEncoding :: Encoding -> (Int, Char)
fromEncoding (Multiple num char) = (num, char)
fromEncoding (Single char) = (1, char)
replicateChars :: (Int, Char) -> [Char]
replicateChars (num, char) = replicate num char
And the output is the expected output "Mississippi", while decode and encode testing correctly via GHCi.