Last active
June 9, 2017 15:43
-
-
Save lloydmeta/087228fd1d22be64cbdd2b2fab360629 to your computer and use it in GitHub Desktop.
Dec to BaseN and back
This file contains 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
module BaseChange where | |
import Data.Foldable (foldl') | |
-- Turns a base 10 number into a list representation in another base | |
-- based on the zero and digit representation you pass in | |
-- :: Integral -> zero -> [digits] -> [representation] | |
decToBaseN :: Integral a => a -> b -> [b] -> [b] | |
decToBaseN i zero digits = if base == 0 then [] else go i [] | |
where | |
base = fromIntegral $ length digits | |
go 0 [] = [zero] | |
go 0 acc = acc | |
go curr acc = | |
let (q, r) = quotRem curr base | |
in go q ((digits !! fromIntegral r) : acc) | |
-- Given a base, a conversion from a to Num a, and a list of a's representing a number | |
-- returns the base 10 representation of that number | |
baseNToDec :: Num i => i -> (a -> i) -> [a] -> i | |
baseNToDec base toInt = foldl' (\acc n -> base * acc + toInt n ) 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment