Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Julia variable to `nothing` using !== or !=

In some Julia code when can see conditional expression such as

if val !== nothing
    dosomething()
end

where val is a variable of type Union{Int,Nothing}

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

like image 757
scls Avatar asked Jul 02 '19 12:07

scls


People also ask

What does === mean in Julia?

=== means that it's actually the same object, i.e. the variables point to the same spot in memory. == means that the objects have the same values.

Is none in Julia?

The Julia equivalent of None is the constant nothing : a value that is returned by expressions and functions which don't have anything interesting to return. In both languages, this value is not printed at an interactive prompt when an expression evaluates to it, but is otherwise just a normal value.


1 Answers

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

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

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.

like image 71
carstenbauer Avatar answered Sep 19 '22 21:09

carstenbauer