Functional Programming with Rillet: Roman Numerals

const of = require('./rillet.js').of;

function roman(number) {
  return of('I').cycle().take(number).join('').
    replace(/IIIII/g, 'V').
    replace(/IIII/g,  'IV').
    replace(/VV/g,    'X').
    replace(/VIV/g,   'IX').
    replace(/XXXXX/g, 'L').
    replace(/XXXX/g,  'XL').
    replace(/LL/g,    'C').
    replace(/LXL/g,   'XC').
    replace(/CCCCC/g, 'D').
    replace(/CCCC/g,  'CD').
    replace(/DD/g,    'M').
    replace(/DCD/g,   'CM');
} // roman

Here’s another little bit of functional programming silliness that, again, I’ve adapted from some Clojure I found in a tweet

Some very nested Clojure

I mentioned before that Lisps are inside out which, of course, this example is almost designed to show off. My JavaScript version is, I submit, undeniably easier to read and understand.

Presentational issues aside, this way of calculating Roman numerals is new to me and I love it. I was given a close cousin of this problem, given a cash amount find the smallest number of notes and coins needed, as coursework for my CSE in Computer Studies back in 1984. I solved that using repeated subtractions, and that’s probably where I’d start today. This approach, treating it as a string substitution problem, while not necessarily “efficient”, is just beautiful.


Tagged code, rillet, javascript, and fp


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired



Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired