Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: Minor tidying)
Line 1,378: Line 1,378:
If we want to assume a default character set, then a general '''toBase''' (Int -> Int -> String) can be also be derived from '''inBaseDigits'''.
If we want to assume a default character set, then a general '''toBase''' (Int -> Int -> String) can be also be derived from '''inBaseDigits'''.


<lang haskell>import Data.Char (intToDigit)
<lang haskell>import Control.Arrow (first)
import Data.Char (intToDigit)
import Data.List (unfoldr)
import Data.List (unfoldr)
import Data.Tuple (swap)


inBaseDigits :: String -> Int -> String
inBaseDigits :: String -> Int -> String
inBaseDigits ds n = reverse $ unfoldr go n
inBaseDigits ds n = reverse $ unfoldr go n
where
where
base = length ds
go x
go x
| 0 < x =
| 0 < x = Just $ first (ds !!) (swap $ quotRem x (length ds))
let (d, r) = quotRem x base
in Just (ds !! r, d)
| otherwise = Nothing
| otherwise = Nothing