Binary digits: Difference between revisions

Content added Content deleted
m (→‎JS ES6: Tidied)
m (→‎JS ES6: Tidied general version)
Line 2,801: Line 2,801:


<lang JavaScript>(() => {
<lang JavaScript>(() => {
"use strict";


// -------------- DIGITS FOR GIVEN BASE --------------
// showBin :: Int -> String
const showBin = n => {
const binaryChar = n => n !== 0 ? '一' : '〇';


// showIntAtBase :: Int -> (Int -> Char) ->
return showIntAtBase(2, binaryChar, n, '');
// Int -> String -> String
};
const showIntAtBase = base =>
// A string representation of n, in the given base,
// using a supplied (Int -> Char) function for digits,
// and a supplied suffix string.
toChr => n => rs => {
const go = ([x, d], r) => {
const r_ = toChr(d) + r;


// showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String
return 0 !== x ? (
go(quotRem(x)(base), r_)
const showIntAtBase = (base, toChr, n, rs) => {
const showIt = ([n, d], r) => {
) : r_;
const r_ = toChr(d) + r;
};
return n !== 0 ? (
showIt(quotRem(n, base), r_)
) : r_;
};
return base <= 1 ? (
'error: showIntAtBase applied to unsupported base'
) : n < 0 ? (
'error: showIntAtBase applied to negative number'
) : showIt(quotRem(n, base), rs);
};


const e = "error: showIntAtBase applied to";
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = (m, n) => [Math.floor(m / n), m % n];


return 1 >= base ? (
// GENERIC FUNCTIONS FOR TEST ---------------------------------------------
`${e} unsupported base`
) : 0 > n ? (
`${e} negative number`
) : go(quotRem(n)(base), rs);
};


// ---------------------- TEST -----------------------
// intercalate :: String -> [a] -> String
const intercalate = (s, xs) => xs.join(s);
const main = () => {
// showHanBinary :: Int -> String
const showHanBinary = n =>
showIntAtBase(2)(
x => 0 !== x ? (
"一"
) : "〇"
)(n)("");


// map :: (a -> b) -> [a] -> [b]
return [5, 50, 9000]
const map = (f, xs) => xs.map(f);
.map(
n => `${n} -> ${showHanBinary(n)}`
)
.join("\n");
};


// unlines :: [String] -> String
const unlines = xs => xs.join('\n');


// --------------------- GENERIC ---------------------
// show :: a -> String

const show = x => JSON.stringify(x);
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = m =>
// The quotient, tupled with the remainder.
n => [Math.trunc(m / n), m % n];


// TEST -------------------------------------------------------------------


return unlines(map(
// MAIN ---
return main();
n => intercalate(' -> ', [show(n), showBin(n)]), [5, 50, 9000]
));
})();</lang>
})();</lang>
{{Out}}
{{Out}}