I am still totally new to julia and very irritated by the following behaviour:
immutable X
x::ASCIIString
end
"Foo" == "Foo"
true
X("Foo") == X("Foo")
false
but with Int instead of ASCIIString
immutable Y
y::Int
end
3 == 3
true
Y(3) == Y(3)
true
I had expected X("Foo") == X("Foo")
to be true. Can anyone clarify why it is not?
Thank you.
Julia have two types of equality comparison:
is(x,y)
function, and the equivalent operator to do this type of comparison is===
operator. The tricky part is that two mutable objects is equal if their memory addresses are identical, but when you compare two immutable objectsis
returns true if contents are the same at the bit level.2 === 2 #=> true, because numbers are immutable
"Foo" === "Foo" #=> false
==
operator or it's equivalentisequal(x,y)
function that is called generic comparison and returns true if, firstly suitable method for this type of argument exists, and secondly that method returns true. so what if that method isn't listed? then==
call===
operator.Now for the above case, you have an immutable type that do not have
==
operator, so you really call===
operator, and it checks if two objects are identical in contents at bit level, and they are not because they refer to different string objects and"Foo" !== "Foo"
EDIT:
as @Andrew mentioned, refer to Julia documentation, Strings are of immutable data types, so why
"test"!=="true" #=> true
? If you look down into structure of a String data type e.g byxdump("test") #=> ASCIIString data: Array(UInt8,(4,)) UInt8[0x74,0x65,0x73,0x74]
, you find that Strings are of composite data types with an importantdata
field. Julia Strings are mainly a sequence of bytes that stores indata
field of String type. andisimmutable("test".data) #=> false