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

后端 未结 4 2035
别跟我提以往
别跟我提以往 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:27

    What about bringing an implicit into scope that would allow you to have new min/max methods on the list.

    Something like:

    object NanAwareMinOrdering extends Ordering[Double] {
        def compare(x: Double, y: Double) = {
          if (x.isNaN()) {
            +1 // without checking x, return y < x
          } else if (y.isNaN()) {
            -1 // without checking y, return x < y
          } else {
            java.lang.Double.compare(x, y)
          }
        }
      }
    
    object NanAwareMaxOrdering extends Ordering[Double] {
      ....
    }
    
    implicit class MinMaxList(list:List[Double]) {
      def min2 = list.min(NanAwareMinOrdering)
      def max2 = list.max(NanAwareMaxOrdering)
    }
    

    List(1.0, 2.0, 3.0, Double.NaN).min2

提交回复
热议问题