diff options
Diffstat (limited to 'Data/BaseConvert.hs')
-rw-r--r-- | Data/BaseConvert.hs | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/Data/BaseConvert.hs b/Data/BaseConvert.hs new file mode 100644 index 0000000..655f593 --- /dev/null +++ b/Data/BaseConvert.hs | |||
@@ -0,0 +1,30 @@ | |||
1 | module Data.BaseConvert (toString, toNum, toAlphaDigit, fromAlphaDigit) where | ||
2 | |||
3 | import Data.Sequence | ||
4 | import Data.Foldable (toList) | ||
5 | import Data.List | ||
6 | import Data.Char | ||
7 | |||
8 | digit_alphabet :: [Char] | ||
9 | digit_alphabet = ['0'..'9'] ++ ['A'..] | ||
10 | |||
11 | toBase :: (Integral a) => a -> a -> [a] | ||
12 | toBase _ 0 = [0] | ||
13 | toBase b v = toList $ | ||
14 | unfoldl (\n -> if n == 0 then Nothing else Just (n `divMod` b)) v | ||
15 | |||
16 | toAlphaDigit :: (Integral a) => a -> Char | ||
17 | toAlphaDigit = (digit_alphabet !!) . fromIntegral | ||
18 | |||
19 | toString :: (Integral a) => a -> a -> String | ||
20 | toString b v = map toAlphaDigit (toBase b v) | ||
21 | |||
22 | fromAlphaDigit :: (Num a) => Char -> a | ||
23 | fromAlphaDigit v = fromIntegral n | ||
24 | where Just n = elemIndex (toUpper v) digit_alphabet | ||
25 | |||
26 | fromBase :: (Num a) => a -> [a] -> a | ||
27 | fromBase b = foldl (\n k -> n * b + k) 0 | ||
28 | |||
29 | toNum :: (Num a) => a -> String -> a | ||
30 | toNum b v = fromBase b (map fromAlphaDigit v) | ||