Skip to content

Instantly share code, notes, and snippets.

@YusukeHosonuma
Last active May 5, 2016 07:44
Show Gist options
  • Save YusukeHosonuma/55b8e8f5ac2927de09c0826d05a51ade to your computer and use it in GitHub Desktop.
Save YusukeHosonuma/55b8e8f5ac2927de09c0826d05a51ade to your computer and use it in GitHub Desktop.
RL encode/decode with doctest
module RLE where
import Data.List ( group, groupBy )
-- | ランレングス圧縮
--
-- >>> rle "AAABBCCCCD"
-- "A3B2C4D1"
--
-- >>> rle "AAAAAAAAAAB"
-- "A10B1"
--
rle :: String -> String
rle = concatMap (\s -> head s : show (length s)) . group
-- | ランレングス復号
--
-- >>> rle' "A3B2C4D1"
-- "AAABBCCCCD"
--
-- >>> rle' "A10B1"
-- "AAAAAAAAAAB"
--
rle' :: String -> String
rle' = concatMap decode . (groupBy g)
where
decode = \x -> let chr = head x
num = toNum (tail x)
in take num $ repeat chr
toNum s = read s :: Int
g = \x y -> isAlpha x && isNum y
isAlpha c = 'A' <= c && c <= 'Z'
isNum c = '0' <= c && c <= '9'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment