在 Scala 中,为什么模式匹配没有选择 NaN?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6908252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:17:45  来源:igfitidea点击:

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

scalapattern-matchingieee-754nan

提问by deltanovember

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

IntelliJ 调试器显示 NaN,但这在我的模式匹配中没有得到。是否有我省略的可能情况

回答by Tomasz Nurkiewicz

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):

根据 IEEE 754 比较 64 位浮点数是一般规则(与 Scala 甚至 Java 无关,请参阅NaN):

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

The idea is that NaNis a marker value for unknownor indeterminate. Comparing two unknown values should always yields falseas they are well... unknown.

这个想法是未知不确定NaN的标记值。比较两个未知值应该总是产生收益,因为它们很好......未知。false



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

如果你想使用模式匹配 with NaN,试试这个:

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

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

但我认为模式匹配将使用严格的双重比较,所以要小心这个结构。

回答by Landei

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

您可以编写一个提取器(根据 bse 的评论更新):

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


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

回答by hammar

Tomasz is correct. You should use isNaNinstead.

托马兹是对的。你应该isNaN改用。

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