Friday, 15 July 2011

Scala TreeMap strangeness; implementing a reverse-order ordering -


I have a map [long, string] , which I want to be repeated in descending order I have keys. The way I decided to do this, it was as follows:

  var m: sorted map [long, string] = treemark. Mautai (L: Long) => M ++ = Map (2L -> "Hello", 1L -> "World", 3L -> "Chris") Println (m) // map (3 -> Chris, 1 -> world, 2 - & gt; hello)  

I'm sure I can not understand Why this does not work and can only assume that I have made some stupid mistake. Of course, the following works:

  var m: sorted map [long, string] = tree mark. Empty (Long: Long) => New Order [Long] {DF (Compare: Long) = -l.compare (a)}) m ++ = Map (2L -> "Hello", 1L -> "World", 3L -> "Chris") println (m) // map (3 -> Chris, 2 -> Hello, 1 - & gt; World) < / Code> 

difficult Let's run that sorting:

  scala> (-3L) .Compare (1l) race 13: int = -1 scale & gt; (-1 L). Comparison (2l) race 14: int = -1  

We therefore conclude that 3 & lt; 1 & lt; 2. Which works the following:

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

Come on, let us To make sure that what we are doing is insert some brackets there

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

Ok, so the answer is clear. You are reducing the result of comparison , and that is why it works, it is something different from the first time.


No comments:

Post a Comment