Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a ListBuffer by Position

Unfortunately, scala.util.parsing.input.Position does not extend Ordering[Position].

To sort a ListBuffer of errors based on their position, I use the following code:

semanticErrors.sortBy(_.pos)(new Ordering[Position] {
  def compare(x: Position, y: Position): Int = x.line - y.line 
}).toList

I'm sure this can be done more elegantly. But how? For example, I noticed that Position implements <. Is there a generic wrapper which turns something that supports < into an Ordering?


Interestingly, this seems to be a lot easier when converting to a List first:

semanticErrors.toList.sort((a, b) => a.pos < b.pos)

But this is probably not the most efficient solution. An in-place sort of the ListBuffer would be ideal.

like image 256
fredoverflow Avatar asked Dec 16 '22 20:12

fredoverflow


2 Answers

You can sort a ListBuffer with the sortWith method:

semanticErrors.sortWith(_.pos < _.pos)
like image 87
drexin Avatar answered Dec 18 '22 10:12

drexin


Use sortWith as drexin says is easiest as a one-off, but a couple of notes:

1) sort is deprecated, so don't use it. The docs tell you to use sortWith instead.

2) Ordering is a typeclass, so things don't extend it (unlike Ordered) . You just need to have one in implicit scope, which would normally be in a companion object. However Position doesn't have a companion. So you can add the implicit yourself:

implicit val posOrd: Ordering[Position] = Ordering.fromLessThan(_ < _)

Then semanticErrors.sortBy(_.pos) should work.

like image 21
Luigi Plinge Avatar answered Dec 18 '22 09:12

Luigi Plinge