Reassigning value of an element in a tuple

question

#1

Hi, I am facing an issue with using tuples in Julia. Here’s what I am doing
temp = [1 2 3]
A = tuple(temp, temp)
B = tuple(A,A,A)

B returns this :
((
[1 2 3],

[1 2 3]),(
[1 2 3],

[1 2 3]),(
[1 2 3],

[1 2 3]))

I understand I can access the elements in B by
B[1][1][1] (which returns 1, as expected)

But if i type B[1][1][1] = 20 in the REPL, I get this :
((
[20 2 3],

[20 2 3]),(
[20 2 3],

[20 2 3]),(
[20 2 3],

[20 2 3]))

Is there a way to change B[1][1][1] without changing the other elements ?
Thanks in advance.


#2

Cross posted from StackOverflow. Please mention that next time.


#3

Use B=(copy(A), copy(A), copy(A)). (BTW, no need for the tuple)

Also please use backticks to quote your code like so:
``` temp = [1 2 3] A = tuple(temp, temp) B = tuple(A,A,A) ```


#4

I did found this useful:

Equal sign (a=b)

  • simple types are deep copied
  • containers of simple types (or other containers) are shadow copied (their internal is only referenced, not copied)

copy(x)

  • simple types are deep copied
  • containers of simple types are deep copied
  • containers of containers: the content is shadow copied (the content of the content is only referenced, not copied)

deepcopy(x)

  • everything is deep copied recursively

#5

That language isn’t really correct, and it makes it sound like these functions (including =) have a lot more magic than they actually do. They do the same thing in every context, so there’s no need to differentiate them. As commented on SO:

This isn’t exactly wrong… because the terminology is meaningless. There is no such thing in Julia as a “simple type”. And the functions are not magic: they do the same thing to every type. a=b sets the value of a to the value of b, copy(a) makes a new type with the same values for the fields, and deepcopy(a) does that copy recursively on each field. The only thing you need to know is that the value of an immutable is its values (fields), whereas the value of a mutable type is its pointer.