Skip to content

Instantly share code, notes, and snippets.

@yurivish
Last active January 24, 2019 03:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yurivish/2411db6d6f2f1f6029a13099022edac5 to your computer and use it in GitHub Desktop.
struct Name{T}
name::T
end
struct Arr{T, N} <: AbstractArray{T, N}
data::Array{T, N}
end
Base.size(A::Arr) = size(A.data)
Base.axes(A::Arr) = axes(A.data)
Base.getindex(A::Arr, i::Int) = A.data[i]
Base.getindex(A::Arr{T, N}, I::Vararg{Int, N}) where {T, N} = A.data[I...]
resolve_index(A, i) = i
resolve_index(A, i::Name) = i.name
function Base.to_indices(A::Arr, inds, I::Tuple{Any, Vararg{Any}})
I′ = Tuple(resolve_index(A, i) for i in I)
to_indices(A.data, inds, I′)
end
function Base.getindex(A::Arr{T, N}, I::Vararg{Any}) where {T, N}
# Resolve any names to indices into the underlying array
I′ = to_indices(A, I)
A.data[I′...]
end
a = Arr([1 2; 3 4])
a[2] # => 2
a[Name(2)] # => 2
# You may need to `]add https://github.com/mbauman/InvertedIndices.jl`
using InvertedIndices
a[Not(2)] # => error
a[Not(Name(2))] # => error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment