Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Haskell Radix Coversion (See related posts)

// converts an integer from base 10 to a string of base x (where 0 > x >= 20)

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'

You need to create an account or log in to post comments to this site.


Click here to browse all 7716 code snippets

Related Posts