Non-decimal radices/Output: Difference between revisions

→‎{{header|Haskell}}: or, generalising and tabulating a little
(Added Kotlin)
(→‎{{header|Haskell}}: or, generalising and tabulating a little)
Line 570:
f :: Int -> IO ()
f n = putStrLn $ " " ++ showOct n "" ++ " " ++ show n ++ " " ++ showHex n ""</lang>
 
Or, generalising and tabulating a little:
<lang haskell>import Data.Monoid ((<>))
import Data.Ord (comparing)
import Data.List (unfoldr, transpose, maximumBy, intercalate)
 
-- ARBITRARY RADICES ----------------------------------------------------------
bases :: [Int]
bases = [2, 7, 8, 10, 12, 16]
 
tableRows :: [[String]]
tableRows = ((([intToDigits] <*> bases) <*>) . return) <$> [1 .. 33]
 
intToDigits :: Int -> Int -> String
intToDigits base n =
let ds = take base (['0' .. '9'] <> ['A' .. 'Z'])
in reverse $
unfoldr
(\x ->
if x > 0
then let (q, r) = quotRem x base
in Just (ds !! r, q)
else Nothing)
n
 
-- TEST AND TABULATION---------------------------------------------------------
table :: String -> [[String]] -> [String]
table delim rows =
intercalate delim <$>
transpose
((\col ->
let width = length (maximumBy (comparing length) col)
justifyRight n c s = drop (length s) (replicate n c ++ s)
in justifyRight width ' ' <$> col) <$>
transpose rows)
 
main :: IO ()
main =
mapM_
putStrLn
(table " " (([(show <$>), (const "----" <$>)] <*> [bases]) <> tableRows))</lang>
{{Out}}
<pre> 2 7 8 10 12 16
---- ---- ---- ---- ---- ----
1 1 1 1 1 1
10 2 2 2 2 2
11 3 3 3 3 3
100 4 4 4 4 4
101 5 5 5 5 5
110 6 6 6 6 6
111 10 7 7 7 7
1000 11 10 8 8 8
1001 12 11 9 9 9
1010 13 12 10 A A
1011 14 13 11 B B
1100 15 14 12 10 C
1101 16 15 13 11 D
1110 20 16 14 12 E
1111 21 17 15 13 F
10000 22 20 16 14 10
10001 23 21 17 15 11
10010 24 22 18 16 12
10011 25 23 19 17 13
10100 26 24 20 18 14
10101 30 25 21 19 15
10110 31 26 22 1A 16
10111 32 27 23 1B 17
11000 33 30 24 20 18
11001 34 31 25 21 19
11010 35 32 26 22 1A
11011 36 33 27 23 1B
11100 40 34 28 24 1C
11101 41 35 29 25 1D
11110 42 36 30 26 1E
11111 43 37 31 27 1F
100000 44 40 32 28 20
100001 45 41 33 29 21</pre>
 
=={{header|HicEst}}==
9,655

edits