Search code examples
compiler-constructionroman-numeralstranslation-scheme

Convert integers to roman numerals using a syntax-directed translation scheme?


The Dragon Book includes an exercise on converting integers to roman numerals using a syntax-directed translation scheme.

How can this be completed?


Solution

  • I would consider parsing from right-to-left.

    First, I would map the units column:

    0 -> ''
    1 -> 'I'
    2 -> 'II'
    3 -> 'III'
    4 -> 'IV'
    ...
    9 -> 'IX'
    

    Then, if there was a second column (e.g. second from the right = tens column), I would use that to map to

    0 -> ''
    1 -> 'X'
    2 -> 'XX'
    ...
    9 -> 'XC'
    

    That would need to be prepended to the initial output.

    Repeat for next columns (hundreds, thousands) until you run out of letters.

    Double-check the number isn't '0' or negative.