I recall reading somewhere that AbstractRange
s must use 1-based indexing, but now I can't find that anywhere. Does anyone know if that is the case?
Can't find it either (and if neither of us can find it, it can't really be claimed to be documented).
The default implementation is 1-based.
There are non-1 based ranges in OffsetArrays.jl
julia> using OffsetArrays
julia> A = OffsetArray(rand(11), -5:5);
julia> I = eachindex(A)
OffsetArrays.IdOffsetRange(values=-5:5, indices=-5:5)
julia> I[-5]
-5
In that case this doesn't look good:
sortperm(r::AbstractRange) = issorted(r) ? (1:1:length(r)) : (length(r):-1:1)
Also won't that method cover step ranges?
related: https://github.com/JuliaLang/julia/pull/39071#issuecomment-1928125865
I thought the same thing, but it's sortperm, not sort, and we can assume indexing is consecutive.
@Andy Dienes Yes, that's why I brought this up
After stumbling across this, I wondered whether sortperm
is supposed to return indices or a permutation?
sortperm(OffsetArray(randn(5), 10))
does return indices
I think issorted(x[sortperm(x)])
should always be true
I agree: https://github.com/JuliaLang/julia/pull/53208/commits/150e61bdcd53853a97936bd48f08924dccfd059a
while on the topic, maybe empty
should be implemented for most range types?
julia> empty(Base.OneTo(10))
Int64[]
julia> empty(1:10)
Int64[]
julia> empty(1:1:10)
Int64[]
seems like those should arguably return Base.OneTo(0)
, 1:0
and 1:1:0
I think the result of empty should be mutable.
empty(v::AbstractVector, [eltype])
Create an empty vector similar to v,
optionally changing the eltype.
similar(array, [element_type=eltype(array)], [dims=size(array)])
Create an uninitialized mutable array with the
given element type and size, based upon the
given source array...
A key observation in OffsetArrays
is that the axes of an OffsetArray
are their own axes. These, therefore, can't be 1-based. Admittedly, offset ranges aren't treated fully consistently in Base (occasionally the offset is ignored, e.g. when comparing the ranges), and Tim Holy had an issue open about handling offset ranges consistently for Julia 2.0
Jishnu Bhattacharya said:
A key observation in
OffsetArrays
is that the axes of anOffsetArray
are their own axes. These, therefore, can't be 1-based.
But is there any good reason for that? It seems unnecessary to me
I think Tim Holy thought carefully about what properties to require, at some point? And maybe the key was something like x[axes(x,1)] .== x
combined with axes(x[ind]) == axes(ind)
? Edit: The docs say the basic axiom is x[inds][j] == x[inds[j]]
, but don't spend any time arguing for why we must accept this.
Would be happier if there was a different set of nice axioms allowing simple UnitRanges, though.
Last updated: Nov 22 2024 at 04:41 UTC