Haskell Radix Conversion


/ Published in: Haskell
Save to your folder(s)

Converts an integer from base 10 to a string of base x (where 0 > x >= 20). The only thing I'd improve is getting rid of all the calls to error. Perhaps hand back a Maybe String that simply hands back Nothing if unable to convert the number.


Copy this code and paste it in your HTML
  1. convertFromDecimal :: Int -> Int -> String -> String
  2. convertFromDecimal num toBase accum
  3. | toBase < 0 = error "base must be greater than zero"
  4. | toBase > 20 = error "base must be <= 20"
  5. | num < 0 = error "number cannot be negative"
  6. | num == 0 = accum :: String
  7. | num > 0 =
  8. let chars = "0123456789ABCDEFGHIJ"
  9. over = num `mod` toBase
  10. remain = num `div` toBase
  11. accum' = (chars !! over) : accum
  12. in
  13. convertFromDecimal remain toBase accum'

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.