Skip to content

Instantly share code, notes, and snippets.

@ndtimofeev
Created April 7, 2018 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndtimofeev/9fe0a01c61987aaed03d2c6473a24bd9 to your computer and use it in GitHub Desktop.
Save ndtimofeev/9fe0a01c61987aaed03d2c6473a24bd9 to your computer and use it in GitHub Desktop.
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