String Encoding - Haskell

Asked

Viewed 306 times

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.

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, but serves as inspiration for a more complete form

if it were my choice I would use a different initial encoding, one that does not involve integer parse

Browser other questions tagged

You are not signed in. Login or sign up in order to post.