Atiyah Elsheikh
Atiyah Elsheikh

Reputation: 578

Declaring alias types for a tuple of fixed or arbitrary size and element types

Edit: Initial question was simple to answer due to a typo in the code, so I updated the question to make it a bit more exotic

Alias types for different views of tuples

How to define an alias type for a tuple with any of the following combination of features:

Here is my attempt. Given the following hint

julia> typeof((1,2,3,4))
NTuple{4, Int64}

I could define an alias type for a fixed size fixed type tuple as follows:

julia> const Tuple4DInt64 = NTuple{4,Int64}

If the type of the elements need to be qualified, then the above code can be modified to

julia> Tuple4D = NTuple{4,T} where T 

This is equivalent to

julia> Tuple4D = NTuple{4,T} where T <: Any

which can be used as follows:

julia> Tuple4D
NTuple{4, T} where T

julia> Tuple4D{Int64} 
NTuple{4, Int64} 

One can ensure the alias type to be a tuple of fixed size but with various arbitrary types of elements as follows

julia> Tuple4D{Any}
NTuple{4, Any}

Qualifying the size of the tuple as a parameter for the type alias is intuitive as well:

julia> TupleNDInt64 = NTuple{N,Int64} where N
Tuple{Vararg{Int64, N}} 

julia> TupleNDInt64{4} 
NTupleNDInt64{4, Int64}

Last case, qualifying both the type and the size as parameters for the alias type, here I am not able to get it right.

Upvotes: 1

Views: 426

Answers (2)

DNF
DNF

Reputation: 12654

You have a typo. It should be NTuple{4, Int64}, with curly braces, not parens. Type parameters normally go inside {}.

Update: You can do TupleNT = NTuple{N,T} where {N,T} as @MarcMush shows, but I think I prefer this syntax:

const Tuple4D{T} = NTuple{4, T}
const TupleInt{N} = NTuple{N, Int}
const TupleNT{N, T} = NTuple{N, T}

I think this is a bit more readable than NTuple{N, T} where {T, N}:

BackwardsTuple{T, N} = NTuple{N, T}
BackwardsTuple{Float32, 7} # switch parameter order
    => NTuple{7, Float32}

Upvotes: 3

MarcMush
MarcMush

Reputation: 1488

If you want multiple parameters, put curly braces around them:

julia> TupleNT = NTuple{N,T} where {N,T}
Tuple{Vararg{T, N}} where {N, T}

julia> TupleTN = NTuple{N,T} where {T,N}
Tuple{Vararg{T, N}} where {T, N}

julia> TupleTN{Int,4} == TupleNT{4,Int} == NTuple{4,Int}
true

Upvotes: 1

Related Questions