使用!==或!=将Julia变量与“ nothing”进行比较 [英] Comparing Julia variable to `nothing` using !== or !=

查看:107
本文介绍了使用!==或!=将Julia变量与“ nothing”进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些Julia代码中,何时可以看到条件表达式,例如

In some Julia code when can see conditional expression such as

if val !== nothing
    dosomething()
end

其中 val 是类型为 Union {Int,Nothing}

的变量之间的区别是什么? > val!==没什么和 val!=没有

What is the difference between conditons val !== nothing and val != nothing?

推荐答案

首先,通常建议使用没有什么来比较是否有什么什么 c 。该特定功能非常有效,因为它基于类型( @edit isothing(nothing)):

First of all, it is generally advisable to use isnothing to compare if something is nothing. This particular function is efficient, as it is soley based on types (@edit isnothing(nothing)):

isnothing(::Any) = false
isnothing(::Nothing) = true

(请注意,什么都没有是类型什么都没有 c的唯一实例。)

(Note that nothing is the only instance of the type Nothing.)

关于您的问题, === == (同样是!== != )是前者检查是否有两件事是 identical ,而后者检查平等。为了说明这种差异,请考虑以下示例:

In regards to your question, the difference between === and == (and equally !== and !=) is that the former checks whether two things are identical whereas the latter checks for equality. To illustrate this difference, consider the following example:

julia> 1 == 1.0 # equal
true

julia> 1 === 1.0 # but not identical
false

请注意,前一个是整数,而后者是一个浮点数。

Note that the former one is an integer whereas the latter one is a floating point number.

两件事相同是什么意思?我们可以参考比较运算符的文档(?=== ):

What does it mean for two things to be identical? We can consult the documentation of the comparison operators (?===):

help?> ===
search: === == !==

  ===(x,y) -> Bool
  ≡(x,y) -> Bool

  Determine whether x and y are identical, in the sense that no program could distinguish them. First the types
  of x and y are compared. If those are identical, mutable objects are compared by address in memory and
  immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes
  called "egal". It always returns a Bool value.

有时,与 === 相比比与 == 进行比较要快,因为后者可能涉及类型转换。

Sometimes, comparing with === is faster than comparing with == because the latter might involve a type conversion.

这篇关于使用!==或!=将Julia变量与“ nothing”进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆