Search code examples
juliaeval

Modifying an Indexed Value in a Vector Stored as an Expression in Julia


I have a Julia vector a defined as follows:

a = [1, 2, 3]

I also have an expression exp stored, which represents the indexing of the second element in vector a:

exp = :(a[2])

Now, I would like to modify the value at the indexed position, i.e., set a[2] to a new value, say 4. However, I am struggling to find the right syntax or method to achieve this.

I've attempted the usual assignment, but it doesn't seem to work as expected:

$exp = 4 # This results in an error

I've also tried using eval, but it doesn't seem to update the vector a:

eval(exp) = 4 # This doesn't update the vector a

Could someone please provide guidance on how to correctly modify the indexed value in the vector a when the index is stored as an expression? Any insights or alternative approaches would be greatly appreciated.


Solution

  • eval an expression using the first one and make there the update.

    a = [1, 2, 3]
    ex = :(a[2])
    eval(:($ex = 4))
    
    a
    #3-element Vector{Int64}:
    # 1
    # 4
    # 3