Julia: Immutable composite types

喜欢而已 提交于 2020-01-03 08:49:13

问题


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



来源:https://stackoverflow.com/questions/33070366/julia-immutable-composite-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!