Created
August 25, 2012 21:56
-
-
Save hallettj/3471332 to your computer and use it in GitHub Desktop.
Haskell library to convert unsigned integers to and from base36 representations
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
-- Converts unsigned integers to and from base36 representations | |
module Numeric.Base36 ( | |
readBase36 | |
, showBase36 | |
) where | |
import Data.Char (isAscii, isLetter, isDigit, ord, chr, toLower) | |
import Numeric (readInt, showIntAtBase) | |
readBase36 :: (Integral a) => String -> [(a, String)] | |
readBase36 = readInt 36 isAsciiAlphaNum digitToInt | |
showBase36 :: (Integral a, Show a) => a -> String -> String | |
showBase36 = showIntAtBase 36 intToDigit | |
isAsciiAlphaNum :: Char -> Bool | |
isAsciiAlphaNum c = isAscii c && (isDigit c || isLetter c) | |
-- Slightly modified from the hexadecimal implementation in Data.Char | |
digitToInt :: Char -> Int | |
digitToInt c | |
| isDigit c = ord c - ord '0' | |
| c >= 'a' && c <= 'z' = ord c - ord 'a' + 10 | |
| c >= 'A' && c <= 'Z' = ord c - ord 'A' + 10 | |
| otherwise = error ("Base36.digitToInt: not a digit " ++ show c) -- sigh | |
intToDigit :: Int -> Char | |
intToDigit n | |
| n < 10 = chr (n + ord '0') | |
| otherwise = chr (n + ord 'a' - 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another win for JavaScript! (p.s. parseInt that with radix 36)