Binary digits: Difference between revisions

Content added Content deleted
m (→‎JS ES6: Tidied)
m (→‎JS ES6: Tidied general version)
Line 2,801:
 
<lang JavaScript>(() => {
"use strict";
 
// TEST ----------------------------------------------------- DIGITS FOR GIVEN BASE --------------
// showBin :: Int -> String
const showBin = n => {
const binaryChar = n => n !== 0 ? '一' : '〇';
 
const// showIntAtBase =:: (base,Int toChr,-> n,(Int rs-> Char) =-> {
return showIntAtBase(2, binaryChar, n, '');
// unlinesInt ::-> [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 <=> 0rs ?=> ({
returnconst ngo !== 0([x, ?d], (r) => {
) : const r_ = toChr(d) + r;
 
// showIntAtBase :: Int -> (Int -> Char) -> Int -> String ->return String0 !== x ? (
showIt go(quotRem(n, 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 unsupported base'";
// quotRem :: Integral a => a -> a -> (a, a)
const quotRem = (m, n) => [Math.floor(m / n), m % n];
 
return base1 <>= 1base ? (
// GENERIC FUNCTIONS FOR TEST ---------------------------------------------
`${e} unsupported base`
) : 0 > n ? (
'error: showIntAtBase applied to `${e} negative number'`
) : showItgo(quotRem(n, )(base), rs);
};
 
// GENERIC FUNCTIONS FOR TEST ---------------------- TEST -----------------------
// intercalate :: String -> [a] -> String
const intercalatemain = (s, xs) => xs.join(s);{
// showBinshowHanBinary :: Int -> String
const showHanBinary = n =>
showIntAtBase(2)(
x => 0 !== x ? (
"一"
) : "〇"
)(n)("");
 
// map :: (a -> b) ->return [a]5, ->50, [b9000]
const map = (f, xs) => xs .map(f);
n => `${n} -> ${showHanBinary(n)}`
)
const unlines = xs => xs .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 showBinquotRem = nm => {
// The quotient, tupled with the remainder.
const quotRem = (m, n) => [Math.floortrunc(m / n), m % n];
 
// TEST -------------------------------------------------------------------
 
return// unlines(map(MAIN ---
return main();
n => intercalate(' -> ', [show(n), showBin(n)]), [5, 50, 9000]
));
})();</lang>
{{Out}}