How to use priority queues in Scala?

Antimony picture Antimony · Feb 18, 2013 · Viewed 13.9k times · Source

I am trying to implement A* search in Scala (version 2.10), but I've ran into a brick wall - I can't figure out how to use Scala's Priority Queue. It seems like a simple task, but searching on Google didn't turn up anything (except for a single code sample that stopped working back in version 2.8)

I have a set of squares, represented by (Int, Int)s, and I need to insert them with priorities represented by Ints. In Python it's pretty simple, since you just have a list of key, value pairs and use the heapq functions to sort it. But it appears that Scala's tuples aren't even comparable.

So how do you do this? I'm surprised by the complete lack of online information, given how simple it should be.

Answer

om-nom-nom picture om-nom-nom · Feb 18, 2013

There is actually pre-defined lexicographical order for tuples -- but you need to import it:

import scala.math.Ordering.Implicits._

Moreover, you can define your own ordering. Suppose I want to arrange tuples, based on the difference between first and second members of the tuple:

scala> import scala.collection.mutable.PriorityQueue
//  import scala.collection.mutable.PriorityQueue

scala> def diff(t2: (Int,Int)) = math.abs(t2._1 - t2._2)
// diff: (t2: (Int, Int))Int

scala> val x = new PriorityQueue[(Int, Int)]()(Ordering.by(diff))
// x: scala.collection.mutable.PriorityQueue[(Int, Int)] = PriorityQueue()

scala> x.enqueue(1 -> 1)

scala> x.enqueue(1 -> 2)

scala> x.enqueue(1 -> 3)

scala> x.enqueue(1 -> 4)

scala> x.enqueue(1 -> 0)

scala> x
// res5: scala.collection.mutable.PriorityQueue[(Int, Int)] = PriorityQueue((1,4), (1,3), (1,2), (1,1), (1,0))