Misunderstanding of the copy() function

copy only copies the outer collection. If the elements are mutable, then effectively what you get is a new collection with fresh pointers to the same mutable objects. Here’s an example of that phenomenon:

julia> x = [[1], [2]];

julia> y = copy(x);

julia> x === y
false

julia> y[1][1] = 100;

julia> x
2-element Vector{Vector{Int64}}:
 [100]
 [2]

There is deepcopy, but it’s not recommended. It’s better to explicitly construct a new object than to use deepcopy.

Maybe a more functional approach would help, like this:

julia> function change_f(ex)
           if ex.args[1] == :a
               :(d($(ex.args[2])))
           elseif ex.args[1] == :b
               :(e($(ex.args[2])))
           else
               ex
           end
       end
change_f (generic function with 1 method)

julia> exs = [:(a(1)) :(b(2)) :(c(3))]
1×3 Matrix{Expr}:
 :(a(1))  :(b(2))  :(c(3))

julia> map(change_f, exs)
1×3 Matrix{Expr}:
 :(d(1))  :(e(2))  :(c(3))

julia> exs
1×3 Matrix{Expr}:
 :(a(1))  :(b(2))  :(c(3))
2 Likes