Understanding immutable tuples and broadcasting assignment

#1

Not related to practical usage, just for conceptual understanding as a newcomer: in julia, named tuples is one of the types that are immutable:

t = (a = rand(2,2), b = rand(3,3))
t.a = rand(2,2) 
#ERROR: setfield! immutable struct of type NamedTuple cannot be changed

however, broadcasting assignment works: t.a .= rand(2,2) changes t.a. I remembered reading from somewhere (cannot find reference now…) that it’s more helpful to think that the “value” of array in julia is not the actual content, but memory address, and in this example, while named tuple are immutable so that its values cannot be changed afterwards, we are not really changing the value with t.a .= rand(2,2) since the “value” is memory address, which is not changed: e.g. confirmed pointer_from_objref(t.a) or pointer(t.a) is not changed with the broadcast assignment. Also, with a regular array a=rand(3,3), a new assignment a=rand(3,3) changes both the content and pointer, while a .= rand(3,3) changes just the value but not the pointer.
Is it a correct understanding? Thanks!

0 Likes

#2

Yes, you have a pretty accurate view.

The immutability is the binding between t.a and the initial object created with rand(2, 2). The syntax t.a = rand(2,2) means to rebind t.a to a new object which is not allowed. t.a .= rand(2,2) on the other hand just modifies the existing object bound to t.a in place.

It says nothing about the mutability

0 Likes

#3

I would just add that you don’t really need to think about memory and pointers — I prefer to think of things in terms of physical objects. A struct can hold any number of objects in its fields. If the struct is immutable, we cannot swap out which object is in a particular field/location… but if it is holding onto mutable objects, then we can change those things. Think of it like it’s holding onto a bag — you can’t swap out which bag it’s holding onto, but you can change what’s in that bag (if, that is, the bag is mutable itself). As with all analogies, there are places this falls down, but I find it to be more helpful than harmful.

Also, I like reading the .= operator as “broadcast into.” It seems to make its semantics clearer in my head. The words “broadcasting assignment” make things more muddled, I think.

5 Likes