What's so hard about equality?

For example, in Javascript [1,2,3] === [1,2,3] and [1,2,3] == [1,2,3] are both false. Even the simpler case of the empty array is also false. The reason being that arrays are reference types and [1,2,3] and [1,2,3] are different as references. Javascript is not unique in this regard and pretty much every language implements equality as being reference equality except for the most basic types like integers and maybe some built-in types.

Why is this the case? What's so hard about making the default equality operator something stronger? So instead of just comparing references why is it so hard to compare structural properties as well?

I know that many languages provide facilities for overloading certain operators to mean something else so that == will mean what you want it to mean instead of the usual weak reference equality. My question is not whether the language provides such facilities but why the default equality operator isn't something more sensible so that [1,2,3] == [1,2,3] evaluates to true by default and requires no programmer intervention.

In python the above example evaluates to true but if you define the following class

class A:
  def __init__(self, prop):
    self.prop = prop

and then compare a = A(1) to b = A(1) then the answer will be false even though structurally a and b are the same and there is no way to tell them apart if all you know is the bit pattern that defines the object.


Not all languages work the way you describe. For example, in Python == is equality and is is reference comparison:

>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True
>>> a is b
False

Not all languages do this. C++ uses == on objects to mean equality (though == on pointers does mean reference equality). I believe (though I'm not fully sure) that the D programming language reserves == for value equality and the is operator for reference equality.

I think this is just a design decision for JavaScript and a few other languages. There is no reason that it has to be this way.


pretty much every language implements equality as being reference equality

As indicated by the types tag on this question, many languages implement equality as a behaviour of the type. This makes sense: most types will have some properties that can change on an instance without the semantic “value” of that instance changing.

So the answer I'd give is: equality is not hard, it is up to the type to define what instances are equal. Any defaults in the absence of such an explicit decision should be conservative.

If you're creating a custom type, that makes it your responsibility to decide; if the language supports inheritance, use that to express your decision that “equality should behave like this other more basic type”. Otherwise, code the equality test explicitly for the type, just as is done for the existing types you believe have the correct behaviour.

链接地址: http://www.djcxy.com/p/73782.html

上一篇: 是==和!=运算符编译器

下一篇: 平等有什么困难?