sortByUncomparableValue

23 Aufrufe
Direkt zur ersten ungelesenen Nachricht

Dennis Haupt

ungelesen,
08.11.2012, 11:35:1308.11.12
an 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

ungelesen,
08.11.2012, 12:27:4508.11.12
an 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

ungelesen,
08.11.2012, 12:29:1108.11.12
an 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

ungelesen,
08.11.2012, 12:32:2808.11.12
an 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
Allen antworten
Antwort an Autor
Weiterleiten
0 neue Nachrichten