views:

302

answers:

1

I have a Map[Long, String] which I would like iterate over in descending order of the keys. The way I chose to do this was as follows:

var m: SortedMap[Long, String] = TreeMap.empty( (l: Long) => -l)
m ++= Map(2L -> "Hello", 1L -> "World", 3L -> "Chris")
println(m) //Map(3 -> Chris, 1 -> World, 2 -> Hello)

I'm really not sure I understand why this didn't work and can only assume I've made some stupid mistake. Of course the following works:

var m: SortedMap[Long, String] = TreeMap.empty( (l: Long) => new Ordered[Long] {
  def compare(a: Long) = -l.compare(a)
})
m ++= Map(2L -> "Hello", 1L -> "World", 3L -> "Chris")
println(m) //Map(3 -> Chris, 2 -> Hello, 1 -> World)
+2  A: 

Tricky. Let's run that sorting:

scala> (-3L).compare(1L)
res13: Int = -1

scala> (-1L).compare(2L)
res14: Int = -1

We, therefore, conclude that 3 < 1 < 2. Which begs the question of why the following works:

def compare(a: Long) = -l.compare(a)

Well, let's put some parenthesis there, to make sure we know what we are doing

def compare(a: Long) = -(l.compare(a))

Ok, the answer, then, is clear. You are inverting the result of compare, and that's why it works. It's something different from what you did the first time.

Daniel
I assumed that the view was applied to the keys both as the target and the parameter of the comparison (i.e. `(-3L).compare(-1L)`
oxbow_lakes