Scala Code Kata Roman Numerals

There’s a Scala User Group in Gothenburg that had several meetings during this summer.  In one of the meetings the group solved a Kata named KataRomanNumerals (A Kata is a small problem that you do over and over again to learn)

The KataRomanNumerals says you should write a function to convert from normal numbers to Roman Numerals: e.g.
     1 –> I
     10 –> X
     7 –> VII

Unfortunately I could not attend at this meeting, so I had to do it on my own during a few summer nights when my family finally was asleep :-) .

Here’s my solution:

  object Program extends Application {

    class RomanInt(number: Int) {

      def toRomanString() = {
        val ones = List("", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX");
        val tens = List("", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC");
        val hundreds = List("", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM");
        val thousands = List("", "M", "MM", "MMM");

        thousands(part(1000)) + hundreds(part(100)) + tens(part(10)) + ones(part(1))
      }

      def part(digit: Int) = {
        number % (digit * 10) / digit
      }

    }

    implicit def Int2RomanInt(number: Int) = new RomanInt(number)

    println(154.toRomanString()) // prints ‘CLVIII’

  }

Here’s the code with better formatting.

Please comment and correct if I didn’t write idomatic Scala or if you have suggestions for improvements.

/Hans

3 Comments

  • 1
    Jörgen Lundberg
    August 10, 2010 - 9:35 am | Permalink

    When scala can figure out the return type you don’t need to specify one. So, in your case you can skip the “:String”, “:Int” and “: RomanInt” from you def’s.

  • 2
    August 12, 2010 - 12:00 pm | Permalink

    Thank you!
    OK, removed. So it got a bit less verbose, but did it really add readability or did it get harder to understand?

    And by the way, I know you have solvd the same problem, where’s your code?

    /Hans

  • 3
    Mats Henricson
    August 10, 2010 - 1:44 am | Permalink

    Snyggt!

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>