Skip to content

Commit

Permalink
add pop!(vector, idx, [default]) (#35513)
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet authored Apr 24, 2020
1 parent 59ac6d1 commit 745ad10
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]).
* The `@view` and `@views` macros now support the `a[begin]` syntax that was introduced in Julia 1.4 ([#35289]).
Expand Down
16 changes: 16 additions & 0 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
15 changes: 15 additions & 0 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down

0 comments on commit 745ad10

Please sign in to comment.