From e49e53698d430882464a31aabc2817f1ff1669b0 Mon Sep 17 00:00:00 2001 From: Rafael Fourquet Date: Thu, 22 Apr 2021 17:25:26 +0200 Subject: [PATCH] add docs, compat, move to abstractarray.jl --- base/abstractarray.jl | 41 +++++++++++++++++++++++++++++++++++++ base/array.jl | 34 ------------------------------ doc/src/base/collections.md | 1 + 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/base/abstractarray.jl b/base/abstractarray.jl index a5782b99e581c..dc5b828ff1140 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -2549,3 +2549,44 @@ function rest(a::AbstractArray{T}, state...) where {T} sizehint!(v, length(a)) return foldl(push!, Iterators.rest(a, state...), init=v) end + + +## keepat! ## + +""" + keepat!(a::AbstractVector, inds) + +Remove the items at all the indices which are not given by `inds`, +and return the modified `a`. +Items which are kept are shifted to fill the resulting gaps. + +`inds` can be either an iterator or a collection of sorted integer indices. +See also [`deleteat!`](@ref). + +!!! compat "Julia 1.7" + This function is available as of Julia 1.7. + +# Examples +```jldoctest +julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5) +3-element Array{Int64,1}: + 6 + 4 + 2 +``` +""" +function keepat!(a::AbstractVector, inds) + isempty(inds) && return a + local prev + i = firstindex(a) + for k in inds + @isdefined(prev) && (prev <= k || throw(ArgumentError("indices must be sorted"))) + if i != k + a[i] = a[k] + end + prev = k + i = nextind(a, i) + end + deleteat!(a, i:lastindex(a)) + return a +end diff --git a/base/array.jl b/base/array.jl index 993f6b3f5ac99..c17d832d391f1 100644 --- a/base/array.jl +++ b/base/array.jl @@ -1367,40 +1367,6 @@ function insert!(a::Array{T,1}, i::Integer, item) where T return a end -""" - keepat!(a::Vector, inds) - -Remove the items at all the indices which are not given by `inds`, and return the modified `a`. -Items which are kept are shifted to fill the resulting gaps. - -`inds` can be either an iterator or a collection of sorted and unique integer indices. -See also [`deleteat!`](@ref). - -# Examples -```jldoctest -julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5) -3-element Array{Int64,1}: - 6 - 4 - 2 -``` -""" -function keepat!(a::AbstractVector, inds) - isempty(inds) && return a - local prev - i = firstindex(a) - for k in inds - @isdefined(prev) && (prev <= k || throw(ArgumentError("indices must be sorted"))) - if i != k - a[i] = a[k] - end - prev = k - i = nextind(a, i) - end - deleteat!(a, i:lastindex(a)) - return a -end - """ deleteat!(a::Vector, i::Integer) diff --git a/doc/src/base/collections.md b/doc/src/base/collections.md index fe4d8f80b1cd0..f8ef12071171a 100644 --- a/doc/src/base/collections.md +++ b/doc/src/base/collections.md @@ -273,6 +273,7 @@ Base.pushfirst! Base.popfirst! Base.insert! Base.deleteat! +Base.keepat! Base.splice! Base.resize! Base.append!