Skip to content

Instantly share code, notes, and snippets.

@djspiewak
Forked from abedra/Bijective.hs
Created April 9, 2012 01:31
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 djspiewak/2340732 to your computer and use it in GitHub Desktop.
Save djspiewak/2340732 to your computer and use it in GitHub Desktop.
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"
@abedra
Copy link

abedra commented Apr 9, 2012

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 typeChar'
Expected type: [t0 -> a0 -> b0]
Actual type: [Char]
In the first argument of (!!)', namelyalphabet'
In the second argument of ($)', namely ((!!) alphabet) (reverse . tail) (map snd options)'
Failed, modules loaded: none.

@abedra
Copy link

abedra commented Apr 9, 2012

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