Created
August 26, 2015 21:50
-
-
Save dela3499/a40d25bebbd2dcb7cb6e to your computer and use it in GitHub Desktop.
Converting to arbitrary base from base 10.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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