O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 12

To Map, or Not to Map

Alongside standard functional idioms, such as for comprehensions and the combinators map and flatMap, Scala supports imperative operations on collections through for loops and the foreach method.

In this puzzler, both kinds of operations--functional and imperative--are used used to print the Roman numeral symbols in ascending order. What is the result of executing the following code in the REPL?

  case class RomanNumeral(symbol: String, value: Int)
    implicit object RomanOrdering extends Ordering[RomanNumeral] {
    def compare(a: RomanNumeral, b: RomanNumeral) = 
      a.value compare b.value
  }
    import collection.immutable.SortedSet
    val numerals = SortedSet(
    RomanNumeral("M"1000), 
    RomanNumeral("C"100),    ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required