Skip to content

Using to_dimension for dimension specific methods #37516

Open
@Tokazama

Description

@Tokazama

I think it would be useful if we had a formally defined to_dimension method that did something like:

@propagate_inbounds function to_dimension(A::AbstractArray{T,N}, d::Integer) where {T,N}
    @boundscheck if d < 1
        error("BoundsError: attempt to access $(typeof(A)) at dimension $d")
    end
    return Int(d)
end

@propagate_inbounds function to_dimension(A::AbstractArray{T,N}, dims::Tuple{Vararg{<:Integer,L}}) where {T,N,L}
    return ntuple(i -> to_dimension(A, getfield(dims, i)), Val(L))
end

This would provide more useful error messages and provide another useful hook into the array interface. For example, methods that have a dimension argument could easily be made type stable with the following:

@propagate_inbounds function to_dimension(A::AbstractArray, ::Val{D}) where {D}
    return to_dimension(A::AbstractArray, D)
end

# 
function dropdims(A; dims)
    d = to_dimension(A, dims)
    ....
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions