Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between double equals and triple equals for String Comparison in Elixir

Tags:

elixir

I was reading a book on Elixir: Introducing Elixir.

On string compare it says that:

Elixir offers two options for comparing string equality, == and === operators. The == operator is generally the simplest though the other produces the same result.

Whats the purpose of having two operators if they mean the same thing?

like image 489
coderVishal Avatar asked Sep 02 '15 07:09

coderVishal


People also ask

What is the difference between double == and triple === equals?

Double Equals ( == ) checks for value equality only. It inherently does type coercion. This means that before checking the values, it converts the types of the variables to match each other. On the other hand, Triple Equals ( === ) does not perform type coercion.

What does the triple equal to comparison operator do?

The comparison operator called as the Identical operator is the triple equal sign “===”. This operator allows for a much stricter comparison between the given variables or values. This operator returns true if both variable contains same information and same data types otherwise return false.

What is triple === in JavaScript?

JavaScript provides three different value-comparison operations: === — strict equality (triple equals) == — loose equality (double equals) Object.is()

Should you use triple equals JavaScript?

In light of this, most JavaScript experts recommend always using the triple-equals operator, and never using double-equals. The triple-equals operator, as you've probably figured out by now, never does type coercion. So whenever you use triple-equals, you're doing an exact comparison of the actual values.


1 Answers

One example that comes to mind is floats - which use the same comparison functions as strings:

iex> 1 == 1    #true iex> 1 == 1.0  #true iex> 1 === 1   #true iex> 1 === 1.0 #false 

And for !==

iex> 1 != 2    #true iex> 1 != 1.0  #false iex> 1 !== 2   #true iex> 1 !== 1.0 #true 

It is worth noting that these functions use the following Erlang expressions:

Elixir | Erlang ==     | == ===    | =:= !=     | /= !==    | =/= 

From the Erlang documentation:

When comparing an integer to a float, the term with the lesser precision is converted into the type of the other term, unless the operator is one of =:= or =/=. A float is more precise than an integer until all significant figures of the float are to the left of the decimal point. This happens when the float is larger/smaller than +/-9007199254740992.0. The conversion strategy is changed depending on the size of the float because otherwise comparison of large floats and integers would lose their transitivity.

like image 56
Gazler Avatar answered Oct 31 '22 21:10

Gazler