[Julia 1.0.2] indexing into UnitRange buggy? (1:4)[6:4] == 6:5

#1

I was trying to index using a UnitRange like list[2:end] then was curious what gonna be happen when my List only has length 1. Thus I began testing with a UnitRange as list which led me to the following strange behaviour.
Version 1.0.2

julia> (1:4)[2:1]
2:1

julia> (1:4)[5:4]
5:4

julia> (1:4)[6:4]
6:5

julia> (1:4)[6:4]
6:5

julia> (1:4)[7:4]
7:6

julia> (1:4)[1:4]
1:4

julia> (1:4)[5:4]
5:4

julia> (1:4)[4:4]
4:4

julia> (1:4)[4]
4

julia> (1:4)[5]
ERROR: BoundsError: attempt to access 4-element UnitRange{Int64} at index [5]
Stacktrace:
 [1] throw_boundserror(::UnitRange{Int64}, ::Int64) at .\abstractarray.jl:484
 [2] getindex(::UnitRange{Int64}, ::Int64) at .\range.jl:597
 [3] top-level scope at none:0

julia> (1:4)[end]
4

julia> (1:4)[5:end]
5:4
#2

n : n - 1 is the canonical representation of an empty UnitRange. In the case of (1:4)[6:4], we have 6:4 === 6:5, and indexing the range 1:4 with an empty range results in an empty range as expected:

julia> isempty((1:4)[6:4])
true

How that empty range is represented (e.g., 6 : 5 or 1 : 0) shouldn’t really matter and probably just follows from the logic for the general case.

3 Likes
#3

This also preserves the nice property of a UnitRange: length = stop - start + 1

2 Likes
#4

In other words, 6:4 and 6:5 are the same cos they are both empty, but 6:-1;4 and 6:-1:5 are different.

1 Like