Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple == Confusion

Tags:

Suppose I define two tuples:

Tuple<float, float, float, float> tuple1 = new Tuple<float, float, float, float>(1.0f, 2.0f, 3.0f, 4.0f);
Tuple<float, float, float, float> tuple2 = new Tuple<float, float, float, float>(1.0f, 2.0f, 3.0f, 4.0f);

If I try to compare the tuples, I get different results

bool result1 = (tuple1 == tuple2);    // FALSE
bool result2 = tuple1.Equals(tuple2); // TRUE

I would expect for both calls to return true. What exactly is == comparing?

like image 918
lumberjack4 Avatar asked Mar 22 '12 16:03

lumberjack4


People also ask

Can we compare 2 tuples in Python?

Practical Data Science using PythonTuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

How do you compare two list tuples in Python?

We can use the Python map() function along with functools. reduce() function to compare the data items of two lists. The map() method accepts a function and an iterable such as list, tuple, string, etc.

Is an object a tuple?

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.


1 Answers

For Tuple, the == is comparing the object references because it does not overload the == operator. Since the objects are equivalent, but not the same specific instance, Equals() returns true and == returns false.

Many types do not overload ==, some prefer to keep a distinction between Equals() for equivalence and == for reference equality.

In addition, relying on == for equivalence can lead to some weirdness:

public bool AreSame<T>(T first, T second) where T : class
{
    return first == second;
}

The code above will always check for reference equality because an unconstrained generic is considered an object at compile time, thus if the method isn't virtual, you will get object's version (even if the type, such as string overloads ==).

Thus this usage of the above code:

var x = "Hello";
var y = "H";

// doing concat to avoid string interring
AreSame(x, y+"ello");

Yes, the strings are equivalent, yes T is string, but the == is bound to object's == since the generic is unconstrained, thus this will return false even though the same code with explicit string parameters would return true.

like image 199
James Michael Hare Avatar answered Oct 30 '22 17:10

James Michael Hare