String Encoding - Haskell

0

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.

    
asked by anonymous 21.07.2017 / 04:29

1 answer

0

This function expands the above compression

u ('!':n:c:oo)=replicate (read [n]) c ++ u oo u (o:oo)=o:u oo

example (ghci): u "asd!4fghjjk!4lpoooi" "asdffffghjjkllllpoooi

is a recursive function and only works if the number of replications is less than 10, however it serves as inspiration for a more complete

If it were my choice I would use a different initial encoding, one that did not involve the parse of the integer

    
23.07.2017 / 06:06