Cantor set: Difference between revisions

→‎{{header|JavaScript}}: Tidied first version, updated its primitives.
(→‎{{header|JavaScript}}: Tidied first version, updated its primitives.)
Line 1,594:
{{Trans|Haskell}}
<lang JavaScript>(() => {
'"use strict'";
 
// --------------------- CANTOR ----------------------
const main = () => {
 
// cantor :: [(Bool, Int)] -> [(Bool, Int)]
const cantor = xs => {
const go = ([bln, n]) =>
bln && 1 < n ? (() => {
const lngx = Math.floor(n / 3);
 
return [
return [true, lng],
[falsetrue, lngx],
[truefalse, lngx],
[true, x]
})() : [
[bln, n]
];
return concatMap})(go, xs); : [
}; [bln, n]
)];
 
//return cantorLines :: Int -> Stringxs.flatMap(go);
};
const cantorLines = n =>
unlines(
map(showCantor,
take(n,
iterate(
cantor,
[
[true, Math.pow(3, n - 1)]
]
)
)
)
);
 
// ---------------------- TEST -----------------------
// showCantor :: [(Bool, Int)] -> String
// main :: IO ()
const showCantor = xs =>
const main = () concat(map(=>
const cantorLines = n =>(5);
([bln, n]) => replicate(n, bln ? '*' : ' '), xs
));
 
console.log(
cantorLines(5)
);
};
 
// GENERIC FUNCTIONS --------------------- DISPLAY ---------------------
 
// concatcantorLines :: [[a]]Int -> [a]String
//const concatcantorLines ::= [String]n -=> String
const concat = xs =>take(n)(
0 < xs.length ? iterate(cantor)() => {[
const unit = 'string' !== typeof xs[0]true, ?3 ** (n - 1)]
[])
) : '';
return unit.concat.applymap(unit, xsshowCantor);
}).join("\n") : [];
 
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const// concatMapshowCantor =:: [(fBool, xsInt)] =-> String
const mainshowCantor = ()xs => {
xs.reduce((a, x) => a.concat(f(x)), []);
consolexs.logmap(
([bln, n]) => replicate(n, bln ? '*' : ' '), xs
mapbln ? (showCantor,
return ["*"
})() : [" "
take).repeat(n,)
);
.join("");
 
// ---------------- GENERIC FUNCTIONS ----------------
 
// iterate :: (a -> a) -> a -> Gen [a]
function*const iterate(f, x)= f {=>
let// vAn =infinite x;list of repeated
while// (true)applications {of f to x.
function* yield(vx); {
let v = f(v)x;
}
}
 
// map :: (a -> b) -> [a] ->while (true) [b]{
const map = (f, xs) => xs.map(f) yield v;
v = [bln, n]f(v);
));}
};
 
// replicate :: Int -> String -> String
const replicate = (n, s) => s.repeat(n);
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = (n, xs) =>
// The first n elements of a list,
'GeneratorFunction' !== xs.constructor.constructor.name ? (
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], ...Array.from({
length: n
}, () => {
const x = xs.next();
 
return x.done ? [] : [x.value];
}));
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// MAIN ---
9,655

edits