Return to Snippet

Revision: 47083
at June 1, 2011 00:26 by rtperson


Initial Code
convertFromDecimal :: Int -> Int -> String -> String
convertFromDecimal num toBase accum
    | toBase < 0 = error "base must be greater than zero"
    | toBase > 20 = error "base must be <= 20"
    | num < 0     = error "number cannot be negative"
    | num == 0 = accum :: String
    | num > 0  = 
        let chars  = "0123456789ABCDEFGHIJ"
            over   = num `mod` toBase
            remain = num `div` toBase
            accum' = (chars !! over) : accum
        in 
            convertFromDecimal remain toBase accum'

Initial URL


Initial Description
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.

Initial Title
Haskell Radix Conversion

Initial Tags


Initial Language
Haskell