Non-decimal radices/Convert: Difference between revisions

→‎{{header|Haskell}}: Deriving toBase :: Int -> Int -> String from inBaseDigits :: [Char] -> Int -> String
m (→‎{{header|Haskell}}: (adjusted the example))
(→‎{{header|Haskell}}: Deriving toBase :: Int -> Int -> String from inBaseDigits :: [Char] -> Int -> String)
Line 1,266:
42</lang>
 
 
ToOr, 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 aan ordered setlist of digits as its first argument, returns an Int -> String unfold function. (The base is the length of the digit setlist).
 
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)
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[Char] -> Int -> String
inBaseDigits ds n =
let base = length ds
Line 1,293 ⟶ 1,303:
inOctal :: Int -> String
inOctal = inBaseDigits "01234567"
 
 
main :: IO ()
main =
mapM_ putStrLn $ [inLowerHex, inUpperHex, inBinary, inOctal] <*> [254]</lang>
[inLowerHex, inUpperHex, inBinary, inOctal, toBase 16, toBase 2] <*> [254]</lang>
 
{{Out}}
Line 1,303 ⟶ 1,313:
FE
11111110
376</pre>
fe</pre>
 
=={{header|HicEst}}==
9,659

edits