scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

Seq.sortWith is not stable, contrary to the documentation #12725

Closed noresttherein closed 1 year ago

noresttherein commented 1 year ago

Reproduction steps

Scala version: 2.13.10

println(List(1, -1).sortWith((x, y) => x*x <= y*y))

Problem

Prints List(-1, 1)

som-snytt commented 1 year ago

The sort is stable. That is, elements that are equal (as determined by lt) appear in the same order in the sorted sequence as in the original.

The doc is not precise, but elements that are mutually lt each other are not equal. Rather, elements for which neither is lt the other are equal. This is different from subset or similar.

scala> def lt(x: Int, y: Int) = x*x <= y*y
def lt(x: Int, y: Int): Boolean

scala> lt(-1, 1)
val res0: Boolean = true

scala> lt(1, -1)
val res1: Boolean = true