Hi everyone,
I’m struggling with the following operation: I have an array of Tuple{Int,String) in which I have to increase by 1 the first element of the tuple but it seems doesn’t work in a while cycle; here the solution I implemented
s=Tuple{Float64,String}
for i in 1:n
push!(s, (0.0,“null”) )
end
for i in 1:n
s[ i ][ 1 ]+=1
end
it gives me error on the setindex, how I’m supposed to do this?Thanks everyone
I am however struggling to see the use-case. Perhaps there is a better approach to what you are tying to do? Perhaps you would find the enumerate function or a 1:n range useful.
Since a Tuple is an immutable container, you can’t change it’s contents once it’s created. You can get around this by creating a new Tuple with the modified contents.
s = Tuple{Float64,String}[]
for i = 1:n
push!(s, (0.0, "null"))
end
for i = 1:n
s[i] = (s[i][1]+1,s[i][2])
end
In rare cases when you have to change the contents after the tuple was created, you can still change the underlying contents of mutable containers inside tuples. But in this case, maybe choosing an Array from the beginning could be better.
s = Tuple{Vector{Float64},String}[]
for i = 1:n
push!(s, ([0.0],"null"))
end
for i = 1:n
s[i][1] .+= 1
end
It’s great to know about such a function; I had no idea it existed because it’s not exported. I usually see it when extending functionality of structs like import Base.setindex; setindex(..) = ...
I think it is a bit confusing, though, because the order of the arguments is not what I would expect. If I’m reading it, I’d compare with the equivalent x[2] = 5, so I’m expecting setindex(x, 2, 5). This is similar to, for example, copyto!(A, Ainds, B, Binds) which means A[Ainds] = B[Binds].
Arguments to setindex are just like getindex, setindex!, view. The index always comes last, because for multi-dimensional objects there will be more than one of them.