Roman numerals/Decode: Difference between revisions

m
No edit summary
 
Line 4,445:
(fold and foldr examples)
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// -------------- ROMAN NUMERALS DECODED ---------------
 
// Folding from right to left,
Line 4,454 ⟶ 4,455:
// fromRoman :: String -> Int
const fromRoman = s =>
foldr(l => ([r, n...s]) => [
l,.map(glyphValue)
l >= r ? .reduceRight(
([r, n], l) => n + l[
) : n - l,
])([0, 0])( l >= r
[...s].map(charVal) ? n + l
I : 1,n - l
a],
V: 5[0, 0]
)[1];
 
// charVal :: Char -> Maybe Int
const charVal = k => {
const v = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
} [k];
return v !== undefined ? v : 0;
};
 
// charValglyphValue :: Char -> Maybe Int
// ----------------------- TEST ------------------------
const mainglyphValue = ()k => [({
);I: 1,
'MDCLXVI', 'MCMXC', 'MMVIII', 'MMXVI', 'MMXVII'
]V: 5,
.map(fromRoman)X: 10,
.join('\n');L: 50,
C: 100,
D: 500,
M: 1000
}) [k] || 0;
 
// ----------------------- TEST ------------------------
 
return main();[
// ----------------- GENERIC FUNCTIONS -----------------
'"MDCLXVI'", '"MCMXC'", '"MMVIII'", '"MMXVI'", '"MMXVII'"
 
};]
// foldr :: (a -> b -> b) -> b -> [a] -> b
.map(fromRoman)
const foldr = f =>
.join("\n");
// Note that that the Haskell signature of foldr
// differs from that of foldl - the positions of
// accumulator and current value are reversed.
a => xs => [...xs].reduceRight(
(a, x) => f(x)(a),
a
);
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
9,659

edits