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 24

Double Trouble

One of the differences between floating-point and integer arithmetic is the existence of the special floating-point value NaN. By and large, this value behaves predictably, but you still need to bear in mind how it can affect affect your code.

This code example sorts two collections of floating-point values. What is the result of executing the following code?

  def printSorted(a: Array[Double]) {
    util.Sorting.stableSort(a)
    println(a.mkString(" "))
  }
    printSorted(Array(7.89Double.NaN1.234.56))
  printSorted(Array(7.891.23Double.NaN4.56))

Possibilities

  1. Prints:
      1.23 4.56 7.89 NaN
      1.23 4.56 7.89 NaN
    
  2. Prints:
      1.23 4.56 7.89 NaN
      1.23 7.89 NaN 4.56
    
  3. Prints:
      NaN 1.23 4.56 7.89
      NaN 1.23 4.56 7.89
    
  4. Prints: ...

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