在Scala中,为什么模式匹配未拾取NaN? [英] In Scala, why is NaN not being picked up by pattern matching?
问题描述
我的方法如下
def myMethod(myDouble: Double): Double = myDouble match {
case Double.NaN => ...
case _ => ...
}
IntelliJ调试器显示NaN,但是在我的模式匹配中没有发现.有没有可能我忽略的情况
The IntelliJ debugger is showing NaN but this is not being picked up in my pattern matching. Are there possible cases I am omitting
推荐答案
这是一个通用规则,如何根据IEEE 754比较64位浮点数(与Scala甚至与Java无关,请参见
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
这个想法是NaN
是 unknown 或 indeterminate 的标记值.比较两个未知值应该总是产生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.
如果要与NaN
一起使用模式匹配,请尝试以下操作:
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.
这篇关于在Scala中,为什么模式匹配未拾取NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!