0
The following code encodes a sequence of equal characters, replacing the sequence with ! na, where n is the number of times the character a is repeated. Note that it only compresses sequences greater 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)
Visualizing:
ghci> comprime "asdffffghjjkllllpoooi"
"asd!4fghjjk!4lpoooi"
My question is: How could I do the opposite? For example, swap ! 4f for ffff? I don’t know how to pick up the character after the '!' and use it as the number of times the next character (in the example, 'f') repeats. I tried using the same code but n made a lot of sense to compiler.