Skip to content

Instantly share code, notes, and snippets.

@dela3499
Created August 26, 2015 21:50
Show Gist options
  • Save dela3499/a40d25bebbd2dcb7cb6e to your computer and use it in GitHub Desktop.
Save dela3499/a40d25bebbd2dcb7cb6e to your computer and use it in GitHub Desktop.
Converting to arbitrary base from base 10.
import Graphics.Element exposing (..)
import String
import Result
import Maybe exposing (withDefault)
main = show (toBase 5 147)
toBase: Int -> Int -> Int
toBase base number =
toBase' base "" number
|> String.toInt
|> Result.toMaybe
|> withDefault 0
toBase': Int -> String -> Int -> String
toBase' base remainders number =
let (divisor, remainder) = getDivisorAndRemainder base number
remainders' = String.append (toString remainder) remainders
in case divisor of
0 -> remainders'
_ -> toBase' base remainders' divisor
getDivisorAndRemainder: Int -> Int -> (Int, Int)
getDivisorAndRemainder base number =
let divisor = floor ((toFloat number) / (toFloat base))
remainder = number - (divisor * base)
in
(divisor, remainder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment