diff --git a/NEWS.md b/NEWS.md index 3edd1fdc46d25..38c6c40ebff29 100644 --- a/NEWS.md +++ b/NEWS.md @@ -122,6 +122,7 @@ New library features * `x::Signed % Unsigned` and `x::Unsigned % Signed` are supported for integer bitstypes. * `signed(unsigned_type)` is supported for integer bitstypes, `unsigned(signed_type)` has been supported. * `accumulate`, `cumsum`, and `cumprod` now support `Tuple` ([#34654]) and arbitrary iterators ([#34656]). +* `pop!(collection, key, [default])` now has a method for `Vector` to remove an element at an arbitrary index ([#35513]). * In `splice!` with no replacement, values to be removed can now be specified with an arbitrary iterable (instead of a `UnitRange`) ([#34524]). diff --git a/base/array.jl b/base/array.jl index 3811e717211c3..35a2c7f06b055 100644 --- a/base/array.jl +++ b/base/array.jl @@ -1129,6 +1129,22 @@ function pop!(a::Vector) return item end +function pop!(a::Vector, i::Integer) + x = a[i] + _deleteat!(a, i, 1) + x +end + +function pop!(a::Vector, i::Integer, default) + if 1 <= i <= length(a) + x = @inbounds a[i] + _deleteat!(a, i, 1) + x + else + default + end +end + """ pushfirst!(collection, items...) -> collection diff --git a/base/dict.jl b/base/dict.jl index 26862fcd4cdb4..e4a201ddbcd56 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -576,6 +576,9 @@ end Delete and return the mapping for `key` if it exists in `collection`, otherwise return `default`, or throw an error if `default` is not specified. +!!! compat "Julia 1.5" + For `collection::Vector`, this method requires at least Julia 1.5. + # Examples ```jldoctest julia> d = Dict("a"=>1, "b"=>2, "c"=>3); diff --git a/test/arrayops.jl b/test/arrayops.jl index 667ca080034f8..fe34db58f5cda 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -466,6 +466,21 @@ end end @test_throws BoundsError insert!(v, 5, 5) end + +@testset "pop!(::Vector, i, [default])" begin + a = [1, 2, 3, 4] + @test_throws BoundsError pop!(a, 0) + @test pop!(a, 0, "default") == "default" + @test a == 1:4 + @test_throws BoundsError pop!(a, 5) + @test pop!(a, 1) == 1 + @test a == [2, 3, 4] + @test pop!(a, 2) == 3 + @test a == [2, 4] + badpop() = @inbounds pop!([1], 2) + @test_throws BoundsError badpop() +end + @testset "concatenation" begin @test isequal([fill(1.,2,2) fill(2.,2,1)], [1. 1 2; 1 1 2]) @test isequal([fill(1.,2,2); fill(2.,1,2)], [1. 1; 1 1; 2 2])