Lambda 用于在将变量传递给函数时检查 NaN 值

huangapple go评论58阅读模式
英文:

Lambda for checking NaN value while passing variable in a function

问题

有没有可以在将其传递给函数时,通过lambda表达式将NaN值替换为0-1的方法?

我知道我可以像这样检查NaN

if (Double.isNaN(variable_name)) 
{
    // 使其变为0或-1
}

但我想使用lambda表达式来实现,就像这样:

function_to_called("variable_string", variable_double); // 如果variable_double是NaN,则进行检查
英文:

Is there any lambda expression through which I can replace the NaN value to 0 or -1 while passing it to a function?

I know I can put a check for NaN like this:

if (Double.isNaN(variable_name))
{
		// make it 0 or -1
}

But I want to do it using lambda expression like

function_to_called("variable_string", variable_double); // have a check if variable double is NaN

答案1

得分: 1

因为在浮点运算中没有内置方法,NaN常量表示的是一种未定义或无法表示的情况。这与特定值如0或-1不同。可以参考这个问题,详细解释了什么是NaN

你需要自己处理,通过编写正确的逻辑在你自己的方法中,就像你已经用if语句做的那样。

英文:

There is no build in method because in Floating-point arithmetic NaN constant represents something which is undefined or unrepresentable. This is not the same as specific value like 0 or -1. See this question which explains what NaN is.

You should handle it yourself by writing the right logic in your own method, like you already did with the if statement.

答案2

得分: 1

你可以直接使用三元运算符 ... ? ... : ... 来替代你的 if 检查,并将其作为 lambda

Function<Double, Double> deNan = n -> Double.isNaN(n) ? -1 : n;

然而,尽管这样简洁明了,但你将不得不在 Function 上调用 apply 方法,而不能直接调用该函数,即你需要这样做:function_to_called("variable_string", deNan.apply(variable_double));。因此,你可能只需将其定义为常规方法,而不是 lambda,这样你就可以这样使用:deNan(variable_double)

另外,正如之前提到的,将 NaN 替换为像 0-1 这样的“特殊”(或不那么特殊)值实际上可能不是一个好主意。相反,最好的做法可能是彻底过滤掉 NaN 值,或者根据你的场景适当地处理它们。

英文:

You could just use a ternary ... ? ... : ... instead of your if check and make that a lambda:

Function&lt;Double, Double&gt; deNan = n -&gt; Double.isNaN(n) ? -1 : n;

However, while this is nice and short, this way you will have to call apply on the Function instead of being able to call the function directly, i.e. you'd have to do function_to_called(&quot;variable_string&quot;, deNan.apply(variable_double));. So instead, you might just define it as a regular method instead of a lambda so you can use it as deNan(variable_double).

Also, as already noted, replacing NaN with a "special" (or not-so-special) value like 0 or -1 might actually not be such a good idea. Instead, it might be better to filter out NaN values entirely, or to handle them "properly", whatever that entails in your scenario.

huangapple
  • 本文由 发表于 2020年9月3日 21:04:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63724267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定