Initialising typed array of tuples of ints

Hi,
I’m coming from Python so I’m not too hot on static types.

I want an array of tuples of Ints. The number of elements in the array will change depending on the data set used, but the tuples will always be 4 ints. I have this code working:

citArr = []

iter = 1
println(citArr)

for i in shapes
    global iter
    println(iter)
    x1 = Int32(round(i[1][1]*100000))
    y1 = Int32(round(i[1][2]*100000))
    x2 = Int32(round(i[end][1]*100000))
    y2 = Int32(round(i[end][1]*100000))

    push!(citArr, (x1,y1,x2,y2))

    iter += 1

end

println(citArr)

which yields an array of type “any”. I’m struggling to initialize an empty array of type Tuple and then push an arbitrary number of tuples to it.

Thanks for any help.

citArr = Array{NTuple{4,Int32},1}()

Since it looks like you’re working with tuples as small vector-like objects, you might find https://github.com/JuliaArrays/StaticArrays.jl useful. For example, instead of a tuple of ints, you could store an SVector{4, Int} which is just as cheap as a tuple but has convenient vector-like methods (like fast matrix-vector multiplication).

You can also use map to construct a concretely-typed vector without having to worry about initializing the type at all:

julia> citArr = map(1:10) do i
         x1 = Int32(1 * i)
         y1 = Int32(2 * i)
         x2 = Int32(3 * i)
         y2 = Int32(4 * i)
         (x1, y1, x2, y2)
       end
10-element Array{NTuple{4,Int32},1}:
 (1, 2, 3, 4)
 (2, 4, 6, 8)
 (3, 6, 9, 12)
 (4, 8, 12, 16)
 (5, 10, 15, 20)
 (6, 12, 18, 24)
 (7, 14, 21, 28)
 (8, 16, 24, 32)
 (9, 18, 27, 36)
 (10, 20, 30, 40)

Note how we got the correct element type for free, and we didn’t have to initialize the collection or push anything.

3 Likes

Thanks for the tips. The StaticArrays look like exactly what I’m after.