在 Scala 中,为什么模式匹配没有选取 NaN?
我的方法如下
def myMethod(myDouble: Double): Double = myDouble match {
case Double.NaN => ...
case _ => ...
}
IntelliJ 调试器显示 NaN,但这在我的模式匹配中没有被拾取。我是否遗漏了可能的情况
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是根据 IEEE 754 比较 64 位浮点数的一般规则(与 Scala 甚至 Java 无关,请参阅 NaN):
这个想法是
NaN
是未知或不确定的标记值。比较两个未知值应该总是产生false
,因为它们是很好......未知的。如果您想将模式匹配与 NaN 一起使用,请尝试以下操作:
但我认为模式匹配将使用严格的双重比较,因此请小心使用此构造。
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):
The idea is that
NaN
is a marker value for unknown or indeterminate. Comparing two unknown values should always yieldsfalse
as they are well... unknown.If you want to use pattern matching with
NaN
, try this:But I think pattern matching will use strict double comparison so be careful with this construct.
您可以编写一个提取器(根据 bse 的评论更新):
You can write an extractor (updated according to bse's comment):
托马斯是正确的。您应该使用
isNaN
代替。Tomasz is correct. You should use
isNaN
instead.