RosettaCodeData/Task/Non-decimal-radices-Convert/Haskell/non-decimal-radices-convert-2.hs
Ingy döt Net b83f433714 tasks a-s
2013-04-10 23:57:08 -07:00

21 lines
621 B
Haskell

import Data.List
import Data.Char
toBase :: Int -> Int -> [Int]
toBase b v = toBase' [] v where
toBase' a 0 = a
toBase' a v = toBase' (r:a) q where (q,r) = v `divMod` b
fromBase :: Int -> [Int] -> Int
fromBase b ds = foldl' (\n k -> n * b + k) 0 ds
toAlphaDigits :: [Int] -> String
toAlphaDigits = map convert where
convert n | n < 10 = chr (n + ord '0')
| otherwise = chr (n + ord 'a' - 10)
fromAlphaDigits :: String -> [Int]
fromAlphaDigits = map convert where
convert c | isDigit c = ord c - ord '0'
| isUpper c = ord c - ord 'A' + 10
| isLower c = ord c - ord 'a' + 10