Non-decimal radices/Convert: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: (adjusted the example))
(→‎{{header|Haskell}}: Deriving toBase :: Int -> Int -> String from inBaseDigits :: [Char] -> Int -> String)
Line 1,266: Line 1,266:
42</lang>
42</lang>



To allow for digit variants like upper case vs lower case Hexadecimal, we can express our conversion function(s) in terms of a more general function which, given a set of digits as its first argument, returns an Int -> String unfold function. (The base is the length of the digit set).
Or, allow for digit variants like upper case vs lower case Hexadecimal, we can express our conversion function(s) in terms of a more general '''inBaseDigits''' function which, given an ordered list of digits as its first argument, returns an Int -> String unfold function. (The base is the length of the digit list).

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.List (unfoldr)
import Data.Char (intToDigit)

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


inBaseDigits :: String -> Int -> String
inBaseDigits :: [Char] -> Int -> String
inBaseDigits ds n =
inBaseDigits ds n =
let base = length ds
let base = length ds
Line 1,293: Line 1,303:
inOctal :: Int -> String
inOctal :: Int -> String
inOctal = inBaseDigits "01234567"
inOctal = inBaseDigits "01234567"



main :: IO ()
main :: IO ()
main =
main =
mapM_ putStrLn $ [inLowerHex, inUpperHex, inBinary, inOctal] <*> [254]</lang>
mapM_ putStrLn $
[inLowerHex, inUpperHex, inBinary, inOctal, toBase 16, toBase 2] <*> [254]</lang>


{{Out}}
{{Out}}
Line 1,303: Line 1,313:
FE
FE
11111110
11111110
376</pre>
376
fe</pre>


=={{header|HicEst}}==
=={{header|HicEst}}==