Elixir 中字符串比较的双等号和三等号之间的区别
Difference between double equals and triple equals for String Comparison in Elixir
我正在阅读一本关于 Elixir 的书:Introducing Elixir。
在字符串比较中说:
Elixir offers two options for comparing string equality, ==
and ===
operators. The ==
operator is generally the simplest though the other produces the same result.
如果两个运算符的意思相同,那有什么用呢?
我想到的一个例子是浮点数——它使用与字符串相同的比较函数:
iex> 1 == 1 #true
iex> 1 == 1.0 #true
iex> 1 === 1 #true
iex> 1 === 1.0 #false
还有 !==
iex> 1 != 2 #true
iex> 1 != 1.0 #false
iex> 1 !== 2 #true
iex> 1 !== 1.0 #true
值得注意的是,这些函数使用了以下Erlang表达式:
Elixir | Erlang
== | ==
=== | =:=
!= | /=
!== | =/=
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.
我正在阅读一本关于 Elixir 的书:Introducing Elixir。
在字符串比较中说:
Elixir offers two options for comparing string equality,
==
and===
operators. The==
operator is generally the simplest though the other produces the same result.
如果两个运算符的意思相同,那有什么用呢?
我想到的一个例子是浮点数——它使用与字符串相同的比较函数:
iex> 1 == 1 #true
iex> 1 == 1.0 #true
iex> 1 === 1 #true
iex> 1 === 1.0 #false
还有 !==
iex> 1 != 2 #true
iex> 1 != 1.0 #false
iex> 1 !== 2 #true
iex> 1 !== 1.0 #true
值得注意的是,这些函数使用了以下Erlang表达式:
Elixir | Erlang
== | ==
=== | =:=
!= | /=
!== | =/=
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.