"=="和"=="之间有什么区别?和"===" Julia中的比较运算符?
Julia中的==
和===
比较运算符有什么区别?
What is the difference between ==
and ===
comparison operators in Julia?
@ChrisRackauckas的答案就其准确性而言是准确的-即,对于可变对象.但是,这个问题还有很多,所以在这里我将详细说明.
@ChrisRackauckas's answer is accurate as far as it goes – i.e. for mutable objects. There's a bit more to the issue than that, however, so I'll elaborate a bit here.
===
运算符(is
函数的别名)实现Henry Baker的EGAL谓词[ 2 ]:当两个对象在程序上无法区分时,x === y
为true –即,您不能编写证明x
和y
之间有任何区别的代码.这归结为以下规则:
The ===
operator (an alias for the is
function) implements Henry Baker's EGAL predicate [1, 2]: x === y
is true when two objects are programmatically indistinguishable – i.e. you cannot write code that demonstrates any difference between x
and y
. This boils down to the following rules:
- 对于可变值(数组,可变复合类型),
===
检查对象身份:如果x
和y
是同一对象,并且存储在内存中的同一位置,则x === y
为true. - 对于不可变的复合类型,如果
x
和y
具有相同的类型(因此具有相同的结构)以及它们的相应组成部分都是递归===
,则x === y
为true. - 对于位类型(不可更改的数据块,如
Int
或Float64
),如果x
和y
包含完全相同的位,则x === y
为true.
- For mutable values (arrays, mutable composite types),
===
checks object identity:x === y
is true ifx
andy
are the same object, stored at the same location in memory. - For immutable composite types,
x === y
is true ifx
andy
have the same type – and thus the same structure – and their corresponding components are all recursively===
. - For bits types (immutable chunks of data like
Int
orFloat64
),x === y
is true ifx
andy
contain exactly the same bits.
这些规则(递归应用)定义了===
的行为.
These rules, applied recursively, define the behavior of ===
.
另一方面,==
函数是用户可定义的,并且实现了抽象值相等".超载能力是主要差异之一:
The ==
function, on the other hand, is user-definable, and implements "abstract value equality". Overloadability is one key difference:
-
===
不可重载-它是具有固定的预定义行为的内置函数.您不能扩展或更改其行为. -
==
是可重载的-它是具有infix语法的常规(对于Julia)常规函数.它具有后备定义,可以为用户定义的类型提供有用的默认行为,但是您可以通过为类型添加新的更具体的方法到==
来更改您认为合适的行为.
- The
===
is not overloadable – it is a builtin function with fixed, pre-defined behavior. You cannot extend or change its behavior. - The
==
is overloadable – it is a normal (for Julia) generic function with infix syntax. It has fallback definitions that give it useful default behavior on user-defined types, but you can change that as you see fit by adding new, more specific methods to==
for your types.