In Scala, why is NaN not being picked up by pattern matching?

霸气de小男生 提交于 2019-12-03 10:35:31

问题


My method is as follows

  def myMethod(myDouble: Double): Double = myDouble match {
    case Double.NaN => ...
    case _ => ...
  }

The IntelliJ debugger is showing NaN but this is not being picked up in my pattern matching. Are there possible cases I am omitting


回答1:


It is a general rule how 64-bit floating point numbers are compared according to IEEE 754 (not Scala or even Java related, see NaN):

double n1 = Double.NaN;
double n2 = Double.NaN;
System.out.println(n1 == n2);     //false

The idea is that NaN is a marker value for unknown or indeterminate. Comparing two unknown values should always yields false as they are well... unknown.


If you want to use pattern matching with NaN, try this:

myDouble match {
    case x if x.isNaN => ...
    case _ => ...
}

But I think pattern matching will use strict double comparison so be careful with this construct.




回答2:


You can write an extractor (updated according to bse's comment):

object NaN {
  def unapply(d:Double) = d.isNaN
}


0.0/0.0 match {
  case NaN() => println("NaN")
  case x => println("boring " + x)
}
//--> NaN



回答3:


Tomasz is correct. You should use isNaN instead.

scala> Double.NaN.isNaN
res0: Boolean = true


来源:https://stackoverflow.com/questions/6908252/in-scala-why-is-nan-not-being-picked-up-by-pattern-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!