I wrote a short Haskell script to compress and decompress via the use of run length encoding.
The concept is simple enough,
n equal items
x in a row will be replaced by
(n, x), decompressing is just the reverse.
> runLengthCompress "foooo barrr" [(1,'f'),(4,'o'),(1,' '),(1,'b'),(1,'a'),(3,'r')]
As you can see the four consecutive
o have been substituted by
About the code itself I fear I have written too little points (arguments) to my functions, hindering readability but I am not sure, maybe the lack of points makes it more readable, not less.
Also I feel like my
areInverses function is already built-in into Haskell and that I am rebuilding the wheel with it.
Without further ado, here is the code:
import Data.List import Control.Monad import Control.Arrow runLengthExpand :: [(Int, a)] -> [a] runLengthExpand = concat . map (uncurry replicate) runLengthCompress :: Eq a => [a] -> [(Int, a)] runLengthCompress = (map (length &&& head)) . group areInverses :: Eq b => (a -> b) -> (b -> a) -> [b] -> Bool areInverses f g = all ((==) =<< f . g) examples :: [[Int]] examples = [ [3, 3, 3, 5, 5, 7, 1], [1,1,1,0,0,0,5] ] main :: IO() main = do print $ runLengthCompress "foooo barrr" print $ areInverses runLengthExpand runLengthCompress examples