Roman Numerals
Write a number from 1 to 3999 in Roman numerals.
Adapted from Exercism’s problem specification (MIT). Listed under Encoding & Ciphers.
// FILE: roman_numerals.nomi
//# Writes numbers as Roman numerals.
once numerals: List<(PositiveInt, String)> = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
/// `number` in Roman numerals. Each numeral, largest first, is written as
/// many times as it fits into what is left.
pub fn roman(number: Int) -> String
(_left, parts) = Iter.map_reduce(numerals, number, fn left, (value, symbol) ->
(left % value, String.repeat(symbol, NonNegativeInt.try_from(left / value)!))
end)
String.join(parts)
end
// FILE: roman_numerals_test.nomi
import roman_numerals
test "converts to Roman numerals"
[
("1 is I", 1, "I"),
("2 is II", 2, "II"),
("3 is III", 3, "III"),
("4 is IV", 4, "IV"),
("5 is V", 5, "V"),
("6 is VI", 6, "VI"),
("9 is IX", 9, "IX"),
("16 is XVI", 16, "XVI"),
("27 is XXVII", 27, "XXVII"),
("48 is XLVIII", 48, "XLVIII"),
("49 is XLIX", 49, "XLIX"),
("59 is LIX", 59, "LIX"),
("66 is LXVI", 66, "LXVI"),
("93 is XCIII", 93, "XCIII"),
("141 is CXLI", 141, "CXLI"),
("163 is CLXIII", 163, "CLXIII"),
("166 is CLXVI", 166, "CLXVI"),
("402 is CDII", 402, "CDII"),
("575 is DLXXV", 575, "DLXXV"),
("666 is DCLXVI", 666, "DCLXVI"),
("911 is CMXI", 911, "CMXI"),
("1024 is MXXIV", 1024, "MXXIV"),
("1666 is MDCLXVI", 1666, "MDCLXVI"),
("3000 is MMM", 3000, "MMM"),
("3001 is MMMI", 3001, "MMMI"),
("3888 is MMMDCCCLXXXVIII", 3888, "MMMDCCCLXXXVIII"),
("3999 is MMMCMXCIX", 3999, "MMMCMXCIX"),
]
|> subtests (description, number, expected), description
assert roman_numerals.roman(number) == expected
end
endok converts to Roman numerals (27 cases)
test result: ok. 27 passed, 0 failed
How it’s written
Section titled “How it’s written”- The numerals, subtractive pairs included, are a
oncetable of(value, symbol)tuples, largest first, annotatedList<(PositiveInt, String)>so each value is a divisor/and%take. - One
Iter.map_reduceover the table: each numeral’s output is its symbol repeatedleft / valuetimes, and the state carried to the next isleft % value. The parts are joined withString.join. AnIter.reducethreading(left, text)and concatenating was the other form; style §33 picksmap_reducewhen each element has its own output and the state only carries what the next one needs. - No validation of the range, since the canonical data has no error cases.
- One
subteststable for all 27 cases.