Skip to content

Instantly share code, notes, and snippets.

@Zambito1
Created June 25, 2018 04:46
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 Zambito1/4d00d871e30c02ce4a2d03c8065ae944 to your computer and use it in GitHub Desktop.
Save Zambito1/4d00d871e30c02ce4a2d03c8065ae944 to your computer and use it in GitHub Desktop.
Converting number bases using Haskell
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