From 27af4e16019400c8c0d6eb3e3be4a5355b11f91b Mon Sep 17 00:00:00 2001 From: Colin Caine Date: Sat, 5 Jun 2021 03:24:44 +0100 Subject: [PATCH] Make Iterators.peel return nothing when itr empty (#39607) Co-authored-by: Jameson Nash --- NEWS.md | 1 + base/iterators.jl | 7 ++++++- test/iterators.jl | 8 ++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 2e10b875e9af5..c6a41f44e00c9 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 ----------------------------- diff --git a/base/iterators.jl b/base/iterators.jl index 8bbd39d689cce..f9728cbbd0793 100644 --- a/base/iterators.jl +++ b/base/iterators.jl @@ -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 @@ -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 diff --git a/test/iterators.jl b/test/iterators.jl index de3dbda921cbd..fb8edcab92209 100644 --- a/test/iterators.jl +++ b/test/iterators.jl @@ -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 \ No newline at end of file