Is there any way to make a first class index that points to an element from the end of an array? So it can be e.g. assigned to a variable. For example, in python I can do
In Julia one can use a special syntax with end keyword to access arrays from the end, but end has its special meaning only inside square brackets. Is there some way, e.g. a special type FromEnd, so I can write
idx = FromEnd(1)
a = [1,2,3,4,5]
a[idx] # Gives 5
indices = CartesianIndex(1):CartesianIndex(FromEnd(1)) # Gives all indices but the last
The answer is no.
There is no firstclass negative index in Julia.
The best you can do is
a[end-(1-1)] for a[-1]
a[end-(2-1)] for a[-2]
a[end-(3-1)] for a[-3]
Cool, thanks. But since UnitRange has kind * → * (i.e. it has only one parameter), it’s fundamentally impossible to write something like x:FromEnd(y), isn’t it?
Well for this to work you’d need to hook into UnitRange and the like which likely will be very messy and doesn’t sound like a great idea to me. The problem is that a UnitRange is concept separate from indexing that doesn’t really make sense without a well-defined endpoint.
Edit: Ofc it’s not “fundamentally impossible” to do what you ask - the question is rather “How much effort do you need?”. For the mixed ranges to work, you probably need another type.
Are you OK with not using the getindex / [ ] syntax directly?
If yes, what about a variation of this (with a better name)?
function getindex_potentially_from_end(a, i)
if i > 0
return a[i]
else
return a[end + i]
end
end
Of course this particular example probably only works with standard 1-based vectors, but it just requires one function and no extra types. Just as an idea.