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.
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.
yeah, that’s a bug. (file an issue)
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
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
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