The following code encodes a string of characters, replacing the sequence with! na, where n is the number of times the character a is repeated. Note that it only compresses sequences larger than 3.
comprime :: String -> String
comprime "" = ""
comprime [c] = [c]
comprime (c:st) = let (seq,rest) = span (==c) (c:st)
len = length seq
in if len > 3 then ("!" ++ show len ++ [c]) ++ comprime rest
else seq++(comprime rest)
Viewing:
ghci> comprime "asdffffghjjkllllpoooi"
"asd!4fghjjk!4lpoooi"
My question is: How could I do the reverse? For example, exchange! 4f for ffff? I do not know how to get the character after the '!' and use it as the number of times the next character (in the example, 'f') repeats. I tried to use the same code but it did not make much sense to the compiler.