Skip to content

Commit

Permalink
Make Iterators.peel return nothing when itr empty (JuliaLang#39607)
Browse files Browse the repository at this point in the history
Co-authored-by: Jameson Nash <[email protected]>
  • Loading branch information
2 people authored and Amit Shirodkar committed Jun 9, 2021
1 parent 7d43584 commit 6ae5ad0
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Language changes
because `x[2]` was mutated during the iteration of `x`. ([#40737])
* The default random number generator has changed, so all random numbers will be different (even with the
same seed) unless an explicit RNG object is used. See the section on the `Random` standard library below.
* `Iterators.peel(itr)` now returns `nothing` when `itr` is empty rather than throwing a `BoundsError`. ([#39569])

Compiler/Runtime improvements
-----------------------------
Expand Down
7 changes: 6 additions & 1 deletion base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,11 @@ rest(itr) = itr
Returns the first element and an iterator over the remaining elements.
If the iterator is empty return `nothing` (like `iterate`).
!!! compat "Julia 1.7"
Prior versions throw a BoundsError if the iterator is empty.
See also: [`Iterators.drop`](@ref), [`Iterators.take`](@ref).
# Examples
Expand All @@ -571,7 +576,7 @@ julia> collect(rest)
"""
function peel(itr)
y = iterate(itr)
y === nothing && throw(BoundsError())
y === nothing && return y
val, s = y
val, rest(itr, s)
end
Expand Down
8 changes: 8 additions & 0 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -853,3 +853,11 @@ end
@testset "proper patition for non-1-indexed vector" begin
@test partition(IdentityUnitRange(11:19), 5) |> collect == [11:15,16:19] # IdentityUnitRange
end

@testset "Iterators.peel" begin
@test Iterators.peel([]) == nothing
@test Iterators.peel(1:10)[1] == 1
@test Iterators.peel(1:10)[2] |> collect == 2:10
@test Iterators.peel(x^2 for x in 2:4)[1] == 4
@test Iterators.peel(x^2 for x in 2:4)[2] |> collect == [9, 16]
end

0 comments on commit 6ae5ad0

Please sign in to comment.