Skip to content

Commit 91505bb

Browse files
authored
Index a CartesianIndex with begin/end (JuliaLang#57985)
Currently, it is possible to index into a `CartesianIndex` using an `Int` index. ```julia julia> I = CartesianIndex(4,3) CartesianIndex(4, 3) julia> I[1] 4 julia> I[2] 3 ``` This PR adds the ability to use `begin`/`end` in the indexing: ```julia julia> I[begin] 4 julia> I[end] 3 ``` The advantage of this (particularly indexing with `end`) is that one doesn't need to know the number of dimensions. This makes writing generic code that accepts either a vector or a matrix easier.
1 parent c5d97f8 commit 91505bb

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

base/multidimensional.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ module IteratorsMD
55
import .Base: eltype, length, size, first, last, in, getindex, setindex!,
66
min, max, zero, oneunit, isless, eachindex,
77
convert, show, iterate, promote_rule, to_indices, copy,
8-
isassigned
8+
isassigned, lastindex, firstindex
99

1010
import .Base: +, -, *, (:)
1111
import .Base: simd_outer_range, simd_inner_length, simd_index, setindex
@@ -103,6 +103,8 @@ module IteratorsMD
103103

104104
# indexing
105105
getindex(index::CartesianIndex, i::Integer) = index.I[i]
106+
firstindex(index::CartesianIndex) = firstindex(index.I)
107+
lastindex(index::CartesianIndex) = lastindex(index.I)
106108
Base.get(A::AbstractArray, I::CartesianIndex, default) = get(A, I.I, default)
107109
eltype(::Type{T}) where {T<:CartesianIndex} = eltype(fieldtype(T, :I))
108110

test/cartesian.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,3 +582,9 @@ end
582582
c = CartesianIndex(3, 3)
583583
@test sprint(show, c) == "CartesianIndex(3, 3)"
584584
end
585+
586+
@testset "CartesianIndex indexing with begin/end" begin
587+
I = CartesianIndex(3,4)
588+
@test I[begin] == I[1]
589+
@test I[end] == I[2]
590+
end

0 commit comments

Comments
 (0)