Assigning values to defined Tuple-array

I am trying to create a tuple-array without assigning values to the tuples. Declaring tuples as an array runs smoothly:

tuples = Array{Tuple{Int, Int},2}
tuples[1] = (1,2)

However, trying to index any elements gives a “no matching setindex”-error. What happens when i declare tuples as an array, and why is it different than directly assigning values upon initialization?

Example, this runs fine:

tuples = [(1,2),(3,2)]
tuples[2]

Not sure I understand the question - are you saying what isn’t working is assigning to an index of an element of your array of tuples like

tup_arr = [(1,2), (3,4)]
tup_arr[1][1] = 5

?

This indeed throws a MethodError: no method matching setindex!, but this is unrelated to having an array of arrays and simply due to the fact that tuples are immutable:

t = (1,2)
t[1] = 5 # MethodError
1 Like

This is a type, not an object.

To be more concrete, I think what you meant to write may have been something like

julia> tuples = Array{Tuple{Int, Int},2}(undef, 1, 1)
1×1 Array{Tuple{Int64,Int64},2}:
 (4627041296, 4630374544)

julia> tuples[1] = (1,2)
(1, 2)

Okay, so by following the typedef with (undef, n, m) it will create an empty nxm Tuple-array?

It will create a n*m Tuple Array with ‘undefined’ contents. I.e. each element will just be a chunk of memory that has been interpreted as a Tuple{Int, Int}, so the contents will look like random garbage.

The beautiful thing about Julia is that you are not forced to fiddle with types if you don’t want to. In your case, for example, you can create a 2-by-3 array of tuples easily like this:

julia> tuples = similar([(0,0)], 2,3)
2×3 Array{Tuple{Int64,Int64},2}:
 (112936112, 94765632)   (94765632, 112941360)   (112514192, 112942032)
 (112514192, 112937040)  (112941488, 112115216)  (94765632, 4294967298)
1 Like