Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize an Empty Array of Tuples in Julia

Tags:

julia

I can't figure out how to initialize an empty array of tuples. The manual says:

The type of a tuple of values is the tuple of types of values... Accordingly, a tuple of types can be used anywhere a type is expected.

Yet this does not work:

myarray = (Int64,Int64)[]

But this does:

Int64[]

It would seem a type is expected in front of the empty square brackets, but the tuple type doesn't work. This <type>[] syntax is the only way I can find to get an empty typed Array (other methods seem to produce a bunch of #undef values). Is the only way to do it, and if it is, how can I type the Array with tuples?

BTW, my use case is creating an array of initially indeterminate length and pushing tuples onto it in a loop.

like image 591
Sean Mackesey Avatar asked Oct 17 '13 05:10

Sean Mackesey


People also ask

How do you initialize an empty array in Julia?

To initialize an empty array, it is perfectly valid to use n = 0 in the above expressions. A possible source of errors would be to confuse this array with an empty array of “Any” type, which is initialized as follows: v = [] # Same as Any[], and you can't change this type easily later (gotcha!)

How would you define tuple in Julia?

Tuples in Julia are an immutable collection of distinct values of same or different datatypes separated by commas. Tuples are more like arrays in Julia except that arrays only take values of similar datatypes. The values of a tuple can not be changed because tuples are immutable.

How do you initialize a vector in Julia?

The easiest way to initialize them are probably list comprehensions, for example: julia> [[Vector{Float64}(undef, 4) for _ = 1:5] for _ = 1:6] 5-element Array{Array{Array{Float64,1},1},1}: ...

How do I add to an array in Julia?

Julia allows adding new elements in an array with the use of push! command. Elements in an array can also be added at a specific index by passing the range of index values in the splice! function.


2 Answers

For people who look for the latest solution,

Tuple{Int, Int}[] works in v0.4

Also the verbose way Array{Tuple{Int, Int}}(0) works in v0.4 as well.

It creates a 0-element Array{Tuple{Int64,Int64},1}

Note that in v1.0 you'd need to write

Array{Tuple{Int, Int}}(undef, 0)

like image 182
colinfang Avatar answered Oct 04 '22 23:10

colinfang


You can do Array((Int,Int),0) for this. It is probably feasible to add methods to getindex to make (Int,Int)[] work, but I'm not sure it's worth it. Feel free to open an issue.

like image 29
StefanKarpinski Avatar answered Oct 04 '22 23:10

StefanKarpinski