Roman Numerals, Revisited
June 3, 2014
We studied the problem of converting between integers and roman numerals in a previous exercise. We’ll do it again today because it’s a fun exercise, it appears frequently in lists of interview questions, we have an improved algorithm, and it lets us highlight a useful piece of the Standard Prelude.
Your task is to write functions that convert an integer to its equivalent in roman numerals and vice versa. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
My C# solution from a while ago: https://gist.github.com/ceottaki/8650187
“Standard” Roman numerals follow the regular expression:
M*((D?C*)|CM|CD)?((L?X*)|XC|XL)?((V?I*)|IX|IV)?
& we can write a simple recognizer, using templates to take advantage of the similarity of the 100s, 10s and 1s parts:
Here’s my Scala solution.
Explicit pattern matching and guards in Erlang make this really easy. The “=” operator in the test function behaves like an assert macro (if the two terms don’t match it throws a run-time exception.)
Erlang command shell: