Skip to content

Commit

Permalink
make firstindex(a,d) and lastindex(a,d) default to calling axes(a,d) (J…
Browse files Browse the repository at this point in the history
  • Loading branch information
stevengj committed Dec 8, 2020
1 parent e585557 commit 8a5ac94
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 3 deletions.
2 changes: 1 addition & 1 deletion NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]).

Expand Down
4 changes: 2 additions & 2 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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))]

Expand Down
4 changes: 4 additions & 0 deletions doc/src/manual/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 8a5ac94

Please sign in to comment.