-
-
Save djspiewak/2340732 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 Data.List | |
import Data.Maybe | |
import Control.Monad | |
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
base = length alphabet | |
encode :: Int -> String | |
encode 0 = "a" | |
encode id = map $ ((!!) alphabet) (reverse . tail) (map snd options) | |
where | |
options = takeWhile (/= (0,0)) (iterate (\x -> ((fst x `div` 62), (fst x `mod` 62))) (id,0)) | |
decode :: String -> Maybe Int | |
decode encoded = do | |
elems <- sequence $ map (\x -> elemIndex x alphabet) encoded | |
return $ foldl (\x y -> x * base + y) 0 elems | |
-- encode 125 | |
-- decode "cb" | |
-- encode 19158 | |
-- decode "e9a" |
After parens update
Prelude> :load bijective [1 of 1] Compiling Main ( bijective.hs, interpreted ) bijective.hs:10:25: Couldn't match expected type `a0 -> b0' with actual type `Char' Expected type: [a0 -> b0] Actual type: [Char] In the first argument of `(!!)', namely `alphabet' In the second argument of `($)', namely `((!!) alphabet) ((reverse . tail) (map snd options))' Failed, modules loaded: none.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prelude> :load bijective.hs
[1 of 1] Compiling Main ( bijective.hs, interpreted )
bijective.hs:10:25:
Couldn't match expected type
t0 -> a0 -> b0' with actual type
Char'Expected type: [t0 -> a0 -> b0]
Actual type: [Char]
In the first argument of
(!!)', namely
alphabet'In the second argument of
($)', namely
((!!) alphabet) (reverse . tail) (map snd options)'Failed, modules loaded: none.