Julia: Immutable composite types

2019-06-18 03:18发布

问题:

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.

回答1:

Julia have two types of equality comparison:

  1. If you want to check that x and y are identical, in the sense that no program could distinguish them. Then the right choice is to use 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 objects is returns true if contents are the same at the bit level.

2 === 2 #=> true, because numbers are immutable

"Foo" === "Foo" #=> false

  1. == operator or it's equivalent isequal(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"

  • Check source Base.operators.jl.
  • Read documentation

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 by xdump("test") #=> ASCIIString data: Array(UInt8,(4,)) UInt8[0x74,0x65,0x73,0x74], you find that Strings are of composite data types with an important data field. Julia Strings are mainly a sequence of bytes that stores in data field of String type. and isimmutable("test".data) #=> false



标签: hash julia