Identity and the is-operatorMay 15. 2012
Identity vs. EqualityThe difference between identity and equality is sometimes subtle but seems to be a very old notion. The German language distinguishes between theese two concepts with the attributes "der gleiche" and "der selbe", which might be translated with "an equal one" and "the identical one". Imagine you see and old blue Mercedes driving along very fast. If you say: "Look, I have an equal one." then you have in mention equality - and have to use the operator ==. But if then your friend answers: "Hey, that is your one!" - then he talks about identity and uses the operator is. In other situations there is no difference between == and is. Imagine another dialog. You: "My sister has 12 cats." Your friend: "My brother has the same number of cats." The numbers of cats of your sister and your friend's brother are both 12. They are equal and also identical. That is because there are not two different twelves - there is just one 12. Identity and equality in WirbelIn Wirbel the most basic datatypes are like the 12 in the upper example. This holds for integers, floats, characters, boolean, enums and bitsets. They are called immutable. On the other hand strings, lists, dicts, tuples and classes are objects with an identity and are mutable. Let's look at an example with immutable values: Immutable
a = 12
b = 12
if a == b: print("We are equal.")
if a is b: print("We are identical.")
If you run that code then you will notice that both messages are printed. Now try the same thing with one-tuples: Mutable
a = (12,)
b = (12,)
if a == b: print("We are equal.")
if a is b: print("We are identical.")
Now a and b are equal but not identical. Only the first message is printed. The syntactical construct (12,) creates a new one-tuple with an own identity. This happens twice here. Changes are reflected in all referencesLet's alter the second example a bit: identity.w a = (12,) b = a Now a and b point to the same, identical one-tuple. That means that any change to that one-tuple will be visible in all references: identity.w a = (12,) b = a b[0] = 13 print(a) let's look a the output user@host> wirbel identity.w (13,) As you can see, a and b are not only equal but even point to the identical tuple object. The statement b[0] = 13 does not assign a new value to b but rather change the thing b points to. |
| |||||||||||||||||||||