sortByUncomparableValue

23 views
Skip to first unread message

Dennis Haupt

unread,
Nov 8, 2012, 11:35:13 AM11/8/12
to scala...@googlegroups.com
let's assume i have a Comparator[X] and a List[Y]

what i want to do is:

ys.sortWith((y1, y2) => xComp.compare(y1.x, y2.x) > 0)

but i don't like > 0, that is so oldschool and low level :( and i might confuse it with < 0. or i did. see? bad code.

is there a better way?

Daniel Sobral

unread,
Nov 8, 2012, 12:27:45 PM11/8/12
to Dennis Haupt, scala-user
ys.sortBy(_.x)

Sorting takes an Ordering, and there's an implicit conversion from Comparator to Ordering. So that ought to work. 
--
Daniel C. Sobral

I travel to the future all the time.

François-Xavier Thomas

unread,
Nov 8, 2012, 12:29:11 PM11/8/12
to Dennis Haupt, scala...@googlegroups.com
There's an Ordered[T] trait, so maybe you can make X and Y inherit from Ordered, override the "compare" method, and get every comparison operator for free?

> scala> case class A(value: Int) extends Ordered[A] { def compare(that: A) = value.compare(that.value) }
> defined class A
>
> scala> val a = new A(1)
> a: A = A(1)
>
> scala> val b = new A(2)
> b: A = A(2)
>
> scala> a < b
> res1: Boolean = true


Cheers,
François-Xavier

François-Xavier Thomas

unread,
Nov 8, 2012, 12:32:28 PM11/8/12
to Daniel Sobral, Dennis Haupt, scala-user
Ah, didn't notice your mail in time Daniel!
Thanks for the tip anyway, I didn't know Comparator was implicitly converted to Ordering.

Cheers,
François-Xavier
Reply all
Reply to author
Forward
0 new messages