Catalan numbers: Difference between revisions

→‎{{header|JavaScript}}: Added a functionally composed variant (for definition three)
(→‎{{header|JavaScript}}: Added a functionally composed variant (for definition three))
Line 3,318:
</pre>
=={{header|JavaScript}}==
 
===Procedural===
<syntaxhighlight lang="javascript"><html><head><title>Catalan</title></head>
<body><pre id='x'></pre><script type="application/javascript">
Line 3,365 ⟶ 3,367:
14 2674440 2674440 2674440
15 9694845 9694845 9694845</pre>
 
===Functional===
 
Defining an infinite list:
 
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// ----------------- CATALAN NUMBERS -----------------
 
// catalansDefinitionThree :: [Int]
const catalansDefinitionThree = () =>
scanlGen(
c => n => Math.floor(
(2 * c * ((2 * n) - 1)) / (1 + n)
)
)(1)(
enumFrom(1)
);
 
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
take(15)(
catalansDefinitionThree()
);
 
// --------------------- GENERIC ---------------------
 
 
// enumFrom :: Enum a => a -> [a]
const enumFrom = function* (x) {
// A non-finite succession of enumerable
// values, starting with the value x.
let v = x;
 
while (true) {
yield v;
v = 1 + v;
}
};
 
 
// scanlGen :: (b -> a -> b) -> b -> Gen [a] -> [b]
const scanlGen = f =>
// The series of interim values arising
// from a catamorphism over an infinite list.
startValue => function* (gen) {
let
a = startValue,
x = gen.next();
 
yield a;
while (!x.done) {
a = f(a)(x.value);
yield a;
x = gen.next();
}
};
 
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : Array.from({
length: n
}, () => {
const x = xs.next();
 
return x.done ? [] : [x.value];
}).flat();
 
 
// MAIN ---
return JSON.stringify(main());
})();</syntaxhighlight>
{{Out}}
<pre>[1,1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440]</pre>
 
=={{header|jq}}==
{{ works with|jq|1.4 }}
9,655

edits