Last active
May 5, 2016 07:44
-
-
Save YusukeHosonuma/55b8e8f5ac2927de09c0826d05a51ade to your computer and use it in GitHub Desktop.
RL encode/decode with doctest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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