Non-decimal radices/Convert: Difference between revisions

→‎{{header|Haskell}}: Generalising to allow for variant digit sets, such as upper case vs lower case Hexadecimal
(Added FreeBASIC)
(→‎{{header|Haskell}}: Generalising to allow for variant digit sets, such as upper case vs lower case Hexadecimal)
Line 1,265:
*Main> fromBase 16 $ fromAlphaDigits $ "2a"
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).
 
<lang haskell>import Data.List (unfoldr)
 
inBaseDigits :: String -> Int -> String
inBaseDigits ds n =
let base = length ds
in reverse $
unfoldr
(\x ->
(if x > 0
then let (d, r) = quotRem x base
in Just (ds !! r, d)
else Nothing))
n
 
inLowerHex :: Int -> String
inLowerHex = inBaseDigits "0123456789abcdef"
 
inUpperHex :: Int -> String
inUpperHex = inBaseDigits "0123456789ABCDEF"
 
inBinary :: Int -> String
inBinary = inBaseDigits "01"
 
inOctal :: Int -> String
inOctal = inBaseDigits "01234567"
 
main :: IO ()
main = mapM_ putStrLn $ [inLowerHex, inUpperHex, inBinary, inOctal] <*> [255]</lang>
 
{{Out}}
<pre>ff
FF
11111111
377</pre>
 
=={{header|HicEst}}==
9,659

edits