Update array

Hi, I am trying to update an array using the following code

add!(z::Val{1}, list, a) = add!(list, a)

 function add!(list, a)
    list = list .+a
   return nothing
 end

However, this does not seem to work well:

list = [1, 2]
a = 1
add!(Val(1), view(list,:), a)
list

The list array does not change to [2,3], I was wondering if anyone knows what is wrong with my code. Thanks!

Try either

 function add!(list, a)
    list .= list .+a
   return nothing
 end

or

 function add!(list, a)
    list .+= a
   return nothing
 end

Here’s a demo:

julia>  function add!(list, a)
           list .= list .+a
          return nothing
        end
add! (generic function with 2 methods)

julia> add!(Val(1), view(list,:), a)

julia> list
2-element Vector{Int64}:
 2
 3

The reason your version does not work is that list .+ a creates a new array, and this array is bound the local variable list, abandoning the array previous bound to list. However, the new list is not returned.

My version updates each element of the original array list by using .= or .+=. I think this is what you want based on the use the exclamation mark.

1 Like

That works, thanks! Actually, list = list.+a outside the function works well, do you happen to know why inside function it fails?

I added an explanation above. Within the function, you are only changing the local variable list. Outside the function list refers to the global variable list.

When you use list = list .+ a you are creating a new array on the right hand side, and then binding that new array to list. Within the function, list is a local variable which is discarded. You would have to specify global list to refer to the global variable. Outside the function, you updating the global binding list to the new array created on the right hand side. The array previously bound to list is discarded.

1 Like

I see, thanks!