Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
No edit summary
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.List (unfoldr)
<lang haskell>import Data.Char (intToDigit)
import Data.Char (intToDigit)
import Data.List (unfoldr)


inBaseDigits :: [Char] -> Int -> String
inBaseDigits :: String -> Int -> String
inBaseDigits ds n =
inBaseDigits ds n = reverse $ unfoldr go n
where
let base = length ds
base = length ds
in reverse $
unfoldr
go x
(\x ->
| 0 < x =
(if x > 0
let (d, r) = quotRem x base
then let (d, r) = quotRem x base
in Just (ds !! r, d)
| otherwise = Nothing
in Just (ds !! r, d)
else Nothing))
n


inLowerHex :: Int -> String
inLowerHex :: Int -> String
Line 1,412: Line 1,410:


toBase :: Int -> Int -> String
toBase :: Int -> Int -> String
toBase intBase n =
toBase intBase n
if (intBase < 36) && (intBase > 0)
| (intBase < 36) && (intBase > 0) =
then inBaseDigits (take intBase (['0' .. '9'] ++ ['a' .. 'z'])) n
inBaseDigits (take intBase (['0' .. '9'] ++ ['a' .. 'z'])) n
else []
| otherwise = []


main :: IO ()
main :: IO ()