Created
June 25, 2018 04:46
-
-
Save Zambito1/4d00d871e30c02ce4a2d03c8065ae944 to your computer and use it in GitHub Desktop.
Converting number bases using Haskell
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 | |
digits = ['0'.. '9'] ++ ['A'.. 'Z'] ++ ['a'.. 'z'] | |
fromBase10 :: Int -> Int -> String | |
fromBase10 0 _ = "" | |
fromBase10 number base | |
| base > 0 = fromBase10 (number `div` base) base ++ [digits !! (number `mod` base)] | |
| otherwise = error "Invalid base" | |
toBase10 :: String -> Int -> Maybe Int | |
toBase10 num base | |
| num == [] || base <=0 = Nothing | |
toBase10 (x:[]) base = x `elemIndex` digits | |
toBase10 (x:xs) base = do digit <- toBase10 [x] base | |
xsVal <- toBase10 xs base | |
return (digit * base ^ (length xs - 1) + xsVal) | |
main = do | |
putStr "Input the base 10 number: " | |
inputNumber <- readLn :: IO Int | |
putStr "Input the target base: " | |
targetBase <- readLn :: IO Int | |
putStrLn $ fromBase10 inputNumber targetBase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment