asdf
asdf

Reputation: 127

Julia: Set index at NTuple

Let's say I have an NTuple with 4 entries of Int64 uninitiallized. How do I set the value of each index separately? I tried the setindex function of base but it didn't work. Any idea?

T = NTuple{4,Int64}
setindex(T,9,2) # set T(2) to 9

Upvotes: 0

Views: 836

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69839

You probably meant NTuple{4, Int64} not Ntuple{4, Int64}.

NTuple is a compact way of representing the type tuples having elements of a single type (not actual values but their types; the thing that might be confusing here is that NTuple{4, Int64} is also technically a value that you can bind to a variable, but this is not what you probably want to do given your question).

You can check this by looking up help on it. In your case it represents a type for a tuple of length 4 and all elements of type Int64. For example (1,2,3,4) is such a tuple. You can check it by writing (1,2,3,4) isa NTuple{4, Int64} which will evaluate to true.

Now if you ask why a tuple like (1,2,3,4) does not support setindex! the reason is that tuples are immutable in Julia, see https://docs.julialang.org/en/latest/manual/types/#Tuple-Types-1. This means that you have to assign a value to each field of a tuple upon its construction and it cannot be mutated.

If you want a mutable container you should probably consider using a vector instead of a tuple. For example:

julia> x = Vector{Int}(undef, 4)
4-element Array{Int64,1}:
 0
 0
 0
 0

julia> x[2] = 9
9

julia> x
4-element Array{Int64,1}:
 0
 9
 0
 0

Upvotes: 3

Related Questions