Skip to content

Commit

Permalink
Make Iterators.peel return nothing when itr empty
Browse files Browse the repository at this point in the history
Fixes JuliaLang#39569.

Old behaviour:
```jl
try
    h, t = Iterators.peel(itr)
    # do something with h and t
catch e
    if e isa BoundsError
        # itr was probably empty
    else
        rethrow()
    end
end
```

New behaviour:
```jl
x = Iterators.peel(itr)
if isnothing(x)
    # itr was empty
end
h, t = x
```
  • Loading branch information
cmcaine committed Feb 11, 2021
1 parent 4a3537b commit 88c2619
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
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

0 comments on commit 88c2619

Please sign in to comment.