Empty range has first element, bug or feature?

I found the following behavoir, which is IMO a bug, but not sure:


julia> isempty(1:0)
true

julia> first(1:0)
1

I would have expected an error.

2 Likes

yeah, that’s a bug. (file an issue)

3 Likes

Is it a bug? Ranges also have a last, step, and length.

julia> r = 1:0
1:0

julia> first(r)
1

julia> last(r)
0

julia> step(r)
1

julia> length(r)
0
1 Like

Semantically it sounds like a bug. An empty collection cannot not have a first or last element I think.
length being equal to zero and step being allowed to have some value sound reasonable though.

I think it is given:

julia> a = 1:0
1:0

julia> collect(a)
Int64[]

julia> first(collect(a))
ERROR: BoundsError: attempt to access 0-element Vector{Int64} at index [1]

having step is fine though.

Turns out its a feature, not a bug: Empty range has first element · Issue #51793 · JuliaLang/julia · GitHub

1 Like

It’s pretty important because it allows you to return useful information from searches where the result is an empty range, because the start of the range tells you the location. For example, searching for word boundaries returns an empty range that has a location:

julia> findnext(r"\b", "foo bar", 2)
4:3
2 Likes