From 8a5ac94e96ec596649384d299ef0c20641e1e165 Mon Sep 17 00:00:00 2001 From: "Steven G. Johnson" Date: Mon, 7 Dec 2020 22:24:07 -0500 Subject: [PATCH] make firstindex(a,d) and lastindex(a,d) default to calling axes(a,d) (#38742) --- NEWS.md | 2 +- base/abstractarray.jl | 4 ++-- doc/src/manual/interfaces.md | 4 ++++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/NEWS.md b/NEWS.md index 51aa50855dc8f..e323fcdb1cfc0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -44,7 +44,7 @@ Language changes a function like other operators. The dotted version `.-->` is now parsed as well. For backwards compatibility, `-->` still parses using its own expression head instead of `:call`. -* The `a[begin]` syntax now calls `firstindex(a,1)` rather than `first(axes(a,1))` ([#35779]). +* The `a[begin, k]` syntax now calls `firstindex(a, 1)` rather than `first(axes(a, 1))` ([#35779]), but the former now defaults to the latter for any `a` ([#38742]). * `⌿` (U+233F) and `¦` (U+00A6) are now infix operators with times-like and plus-like precedence, respectively. Previously they were parsed as identifier characters ([#37973]). diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 85edfe113fcb2..bb697ca11bc14 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -345,7 +345,7 @@ julia> lastindex(rand(3,4,5), 2) ``` """ lastindex(a::AbstractArray) = (@_inline_meta; last(eachindex(IndexLinear(), a))) -lastindex(a::AbstractArray, d) = (@_inline_meta; last(axes(a, d))) +lastindex(a, d) = (@_inline_meta; last(axes(a, d))) """ firstindex(collection) -> Integer @@ -363,7 +363,7 @@ julia> firstindex(rand(3,4,5), 2) ``` """ firstindex(a::AbstractArray) = (@_inline_meta; first(eachindex(IndexLinear(), a))) -firstindex(a::AbstractArray, d) = (@_inline_meta; first(axes(a, d))) +firstindex(a, d) = (@_inline_meta; first(axes(a, d))) first(a::AbstractArray) = a[first(eachindex(a))] diff --git a/doc/src/manual/interfaces.md b/doc/src/manual/interfaces.md index 88b85dd80c3e3..725913876bee1 100644 --- a/doc/src/manual/interfaces.md +++ b/doc/src/manual/interfaces.md @@ -193,6 +193,10 @@ julia> Squares(23)[end] 529 ``` +For multi-dimensional `begin`/`end` indexing as in `a[3, begin, 7]`, for example, +you should define `firstindex(a, dim)` and `lastindex(a, dim)` +(which default to calling `first` and `last` on `axes(a, dim)`, respectively). + Note, though, that the above *only* defines [`getindex`](@ref) with one integer index. Indexing with anything other than an `Int` will throw a [`MethodError`](@ref) saying that there was no matching method. In order to support indexing with ranges or vectors of `Int`s, separate methods must be written: