BenLauwens / ThinkJulia.jl

Port of the book Think Python to the Julia programming language
Other
538 stars 136 forks source link

Object identity #60

Open andyferris opened 1 year ago

andyferris commented 1 year ago

In Chapter 10 it is written:

In this example, Julia only created one string object, and both a and b refer to it. But when you create two arrays, you get two objects:

Actually, this is a misunderstanding of the === operator. For fully immutable values (for example isbitstype types), the objects don't really have any identity to worry about and === will just compare the literal binary bits of the value. For example if you pass a Bool or Int64 from one function to another, these will generally be copied but different copies are ===.

Functionally, the === actually does something similar for objects with identity, or those objects containing pointers to other mutable objects - it compares the bit value of the pointers. If they literally are the same bits of data, then there is no distinction that could be observed by the user, and the objects are ===.

Where the explanation goes wrong is it fails to note that String is a built-in type that is enforced to be immutable, and === compares the contents of two strings not the pointers. (You can observe the difference if you grab the pointers and use unsafe operations to manipulate the underlying RAM). At this level of discussion it might be helpful to focus on really obviously mutable values like Array. Something like this:

To check whether two variables refer to the same object, you can use the (\equiv TAB) or === operator.

julia> a = [1, 2, 3];

julia> b = b;

julia> a ≡ b
true

In this example, Julia only created one array object, and both a and b refer to it. But when you create two arrays, you get two objects:

julia> a = [1, 2, 3];

julia> b = [1, 2, 3];

julia> a ≡ b
false
stevengj commented 5 months ago

I would also use === in examples (which is far more common than in idiomatic Julia code), and mention in passing that one can optionally use .

In general, it's important to emphasize that the use of non-ASCII symbols as identifiers in Julia is optional, and newcomers should not be scared off by the concern that they will be forced to learn new input methods or switch to new editors. They should be exposed to Unicode symbols, as it's common to see Julia code using things like α and λ, and learn that there's nothing to be scared of, but not required to use them. See also #61.