Vector with negative indices extending getindex

In fact, the suggested function already exists in Base (in some capacity)

julia> A = 11:15
11:15

julia> get(A,1,0) # returns A[1]
11

julia> get(A,-3,zero(eltype(A))) # A[-3] is not defined so returns `zero(eltype(A))`
0

get is generally used to access a particular index/key from a collection or to return the default if the index/key is not present. But you’ll have to write your own (as in the above suggestion) if you still want it to error for too-big indices.

By the way, your initial attempt to overload Base.getindex is an example of type piracy and is very dangerous for the reasons you discovered. It changes how the function works everywhere, which is a recipe for chaos. Even if it didn’t produce an error, it might break functionality in more subtle ways (which is even worse because it may be hard to notice).

But if you need this to apply to getindex or its syntax (i.e., A[i]), specifically, and can’t simply use a different access function (like get or your own version), then you’ll need to define a new type of array to do it safely. Making simple types is usually fairly easy. In this case, you may want to reference and follow the array interface.

2 Likes