Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Iterators.peel return nothing when itr empty #39607

Merged
merged 2 commits into from
Jun 5, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ New language features
Language changes
----------------

* `Iterators.peel(itr)` now returns `nothing` when `itr` is empty rather than throwing a `BoundsError`. ([#39569])

Compiler/Runtime improvements
-----------------------------
Expand Down
4 changes: 3 additions & 1 deletion base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,8 @@ rest(itr) = itr

Returns the first element and an iterator over the remaining elements.

If the iterator is empty, returns `nothing` (like `iterate`).

# Examples
```jldoctest
julia> (a, rest) = Iterators.peel("abc");
Expand All @@ -571,7 +573,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 @@ -848,3 +848,11 @@ end
@test cumprod(x + 1 for x in 1:3) == [2, 6, 24]
@test accumulate(+, (x^2 for x in 1:3); init=100) == [101, 105, 114]
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
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grep didn't find any existing tests of Iterators.peel, so I added a few simple ones. I'm using the arrow syntax so the characters line up better, making it clearer when I'm calling with the same arguments.