min/max of collections containing NaN (handling incomparability in ordering)

后端 未结 4 2039
别跟我提以往
别跟我提以往 2021-02-14 00:38

I just ran into a nasty bug as a result of the following behavior:

scala> List(1.0, 2.0, 3.0, Double.NaN).min
res1: Double = NaN

scala> List(1.0, 2.0, 3.0         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-14 01:26

    This answer is simply for explaining the issue, @monkjack's answer probably provides the best practical solution.

    Now since Scala offers the possibility to implicitly pass such an ordering, isn't it a natural desire to pass an ordering, which can handle "incomparability" according to our demands

    Ordering in Scala represents only total orderings, i.e. ones where all elements are comparable. There is a PartialOrdering[T]: http://www.scala-lang.org/api/2.10.3/index.html#scala.math.PartialOrdering, but there are a couple of problems:

    1. It is not actually used anywhere in the standard library.

    2. If you try to implement max/maxBy/etc. which take PartialOrdering, you'll quickly see that it isn't generally possible except in cases like Float/Double where you have some elements which aren't comparable with anything and all the rest are comparable with each other (and you can decide to just ignore the incomparable elements).

提交回复
热议问题