Created
April 7, 2018 12:25
-
-
Save ndtimofeev/9fe0a01c61987aaed03d2c6473a24bd9 to your computer and use it in GitHub Desktop.
This file contains 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
import Control.Monad | |
import Data.List | |
dict = ['a' .. 'z'] | |
base = length dict + 2 | |
encode :: String -> Int | |
encode = fst . foldl go (0, 0) | |
where | |
go (acc, p) v = | |
let Just i = findIndex (v==) dict | |
in (acc + (i + 1) * base ^ p, p + 1) | |
decode :: Int -> String | |
decode = unfoldr go | |
where | |
go r = do | |
let (r', s) = r `divMod` base | |
guard (s /= 0) | |
Just (dict !! (s - 1), r') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment