Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d357579

Browse files
committedOct 24, 2020
add tests and docs for Base.rest
1 parent c6fa3aa commit d357579

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed
 

‎base/tuple.jl

+27
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,33 @@ function indexed_iterate(I, i, state)
9696
x
9797
end
9898

99+
"""
100+
Base.rest(collection[, itr_state])
101+
102+
Generic function for taking the tail of `collection`, starting from a specific iteration
103+
state `itr_state`. Return a `Tuple`, if `collection` itself is a `Tuple`, a `Vector`, if
104+
`collection` is an `AbstractArray` and `Iterators.rest(collection[, itr_state])` otherwise.
105+
Can be overloaded for user-defined collection types to customize the behavior of slurping
106+
in assignments, like `a, b... = collection`.
107+
108+
!!! compat "Julia 1.6"
109+
`Base.rest` requires at least Julia 1.6.
110+
111+
# Examples
112+
```jldoctest
113+
julia> a = [1 2; 3 4]
114+
2×2 Matrix{Int64}:
115+
1 2
116+
3 4
117+
118+
julia> first, state = iterate(a)
119+
(1, 2)
120+
121+
julia> first, Base.rest(a, state)
122+
(1, [3, 2, 4])
123+
```
124+
"""
125+
function rest end
99126
rest(t::Tuple) = t
100127
rest(t::Tuple, i::Int) = ntuple(x -> getfield(t, x+i-1), length(t)-i+1)
101128
rest(a::Array, i::Int=1) = a[i:end]

‎doc/src/base/collections.md

+1
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ Base.filter!
138138
Base.replace(::Any, ::Pair...)
139139
Base.replace(::Base.Callable, ::Any)
140140
Base.replace!
141+
Base.rest
141142
```
142143

143144
## Indexable Collections

‎test/abstractarray.jl

+7
Original file line numberDiff line numberDiff line change
@@ -1193,3 +1193,10 @@ end
11931193
@test last(itr, 1) == [itr[end]]
11941194
@test_throws ArgumentError last(itr, -6)
11951195
end
1196+
1197+
@testset "Base.rest" begin
1198+
a = reshape(1:4, 2, 2)'
1199+
@test Base.rest(a) == a[:]
1200+
_, st = iterate(a)
1201+
@test Base.rest(a, st) == [3, 2, 4]
1202+
end

‎test/tuple.jl

+18
Original file line numberDiff line numberDiff line change
@@ -575,3 +575,21 @@ end
575575
@test_throws BoundsError (1,2.0)[0:1]
576576
@test_throws BoundsError (1,2.0)[0:0]
577577
end
578+
579+
@testset "Base.rest" begin
580+
t = (1, 2.0, 0x03, 4f0)
581+
@test Base.rest(t) === t
582+
@test Base.rest(t, 2) === (2.0, 0x03, 4f0)
583+
584+
a = [1 2; 3 4]
585+
@test Base.rest(a) == a[:]
586+
@test pointer(Base.rest(a)) != pointer(a)
587+
@test Base.rest(a, 3) == [2, 4]
588+
589+
itr = (-i for i in a)
590+
@test Base.rest(itr) == itr
591+
_, st = iterate(itr)
592+
r = Base.rest(itr, st)
593+
@test r isa Iterators.Rest
594+
@test collect(r) == -[3, 2, 4]
595+
end

0 commit comments

Comments
 (0)
Please sign in to comment.