How to get the index type of an array <: AbstractArray?

array
type

#1

A sparse matrix is parameterized by two types: an integer type for the indexes, and a value type. It is trivial to get the type of the latter (eltype(A)), but I have not found a portable way of getting the index type that works generically across all arrays.

It can be argued that some arrays (dense arrays in particular) do not have an index type, but in fact maybe they sort of do (it’s probably the system Int).

Is there a way to get the type parameterization of the index type of an array that doesn’t rely on the internal representation of the structure?


#2

I haven’t seen something in Base to do what you’re asking, but I have done this before:

get_parameter(o::SomeParameterizedType{T}) = T

#3

This probably isn’t news to you, but it is always preferable to do

function f{T}(x::SomeType{T})
    # do stuff with T
end

rather than

function f(x::SomeType)
    T = get_parameter(typeof(x))
    # do stuff with T
end

This is because in the former case the compiler knows what T is. I suspect that the reason there aren’t lots of generic functions sitting around in Base for inferring type parameters is because the devs want to discourage code like my second example. I know that your use case is the index type of sparse matrices, but do you have a specific reason why you don’t want to use the function boundaries to get the type parameter for you?

Addendum: this is incorrect in the particular case of get_parameter, see @mbauman’s comment below.


#4

@ExpandingMan that’s not true.

Sparse Matrices don’t exploit this in their implementation, but you could use eltype.(indices(A)).


#5

Hm… now that I think about it I guess that makes sense. I usually think of type parameters introduced in a function body as being run-time variables that aren’t known to the compiler, but I guess if they are in turn being produced by a function where they originated as a type parameter (and are therefore known to the compiler) that isn’t a problem.

Just to expand on this a little: in data applications we are sometimes in the unfortunate position of having datatypes stored in some Vector{DataType} which then have to be used later. In these cases, we have to be really careful about function boundaries because the compiler does not know what DataType is getting fetched from the Array. This leads me to be paranoid so that I’d be really uncomfortable using get_parameter even though, as we’ve seen, there’s absolutely nothing wrong with it.

Apologies for the misinformation.