Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: added/changed whitespace, used templates for the output sections.)
m (→‎{{header|Haskell}}: inBaseDigits version: Data.Bifunctor in lieu of Control.Arrow)
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 Control.Arrow (first)
<lang haskell>import Data.Bifunctor (first)
import Data.Char (intToDigit)
import Data.List (unfoldr)
import Data.List (unfoldr)
import Data.Tuple (swap)
import Data.Tuple (swap)
import Data.Bool (bool)



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


inLowerHex :: Int -> String
inLowerHex :: Int -> String
inLowerHex = inBaseDigits "0123456789abcdef"
inLowerHex = inBaseDigits "0123456789abcdef"

inUpperHex :: Int -> String
inUpperHex :: Int -> String
inUpperHex = inBaseDigits "0123456789ABCDEF"
inUpperHex = inBaseDigits "0123456789ABCDEF"

inBinary :: Int -> String
inBinary :: Int -> String
inBinary = inBaseDigits "01"
inBinary = inBaseDigits "01"

inOctal :: Int -> String
inOctal :: Int -> String
inOctal = inBaseDigits "01234567"
inOctal = inBaseDigits "01234567"

inDevanagariDecimal :: Int -> String
inDevanagariDecimal :: Int -> String
inDevanagariDecimal = inBaseDigits "०१२३४५६७८९"
inDevanagariDecimal = inBaseDigits "०१२३४५६७८९"

inHinduArabicDecimal :: Int -> String
inHinduArabicDecimal :: Int -> String
inHinduArabicDecimal = inBaseDigits "٠١٢٣٤٥٦٧٨٩"
inHinduArabicDecimal = inBaseDigits "٠١٢٣٤٥٦٧٨٩"

toBase :: Int -> Int -> String
toBase :: Int -> Int -> String
toBase intBase n
toBase intBase n
Line 1,413: Line 1,418:
inBaseDigits (take intBase (['0' .. '9'] ++ ['a' .. 'z'])) n
inBaseDigits (take intBase (['0' .. '9'] ++ ['a' .. 'z'])) n
| otherwise = []
| otherwise = []

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