Is there a general way to create a new tuple from an existing one of any length where one the element is set to something else?
One conceptually simple way (for named tuples) is
julia> nt = (a=2, b=3, c=4)
(a = 2, b = 3, c = 4)
julia> nt2 = (nt..., b=10)
(a = 2, b = 10, c = 4)
1 Like
There is Base.setindex
:
julia> tup = (1, 2, 3)
julia> Base.setindex(tup, "abc", 2)
(1, "abc", 3)
Also, Accessors.jl
is the package to do similar things, if more functionality is needed:
julia> using Accessors
julia> tup = (1, 2, 3)
julia> @set tup[2] = "abc"
(1, "abc", 3)
julia> @insert tup[2] = "abc"
(1, "abc", 2, 3)
3 Likes
Great. Is there a similar way for unnamed tuples as well?
Oh, sorry, I misread your question and thought you were interested in the named tuple case. For regular tuples I don’t know a nice oneliner from the top of my head.
newtup(x,i,y) = (x[1:i-1]...,y,x[i+1:end]...)
newtup((1,2,3,4,5,6,7,8,9,10), 3, 11)
this seems to work
1 Like