diff --git a/base/array.jl b/base/array.jl index 8954f3e5b9d23..903fdc6b5ca05 100644 --- a/base/array.jl +++ b/base/array.jl @@ -946,19 +946,23 @@ function push!(a::Array{Any,1}, @nospecialize item) end """ - append!(collection, collection2) -> collection. + append!(collection, collections...) -> collection. -For an ordered container `collection`, add the elements of `collection2` to the end of it. +For an ordered container `collection`, add the elements of each `collections` +to the end of it. + +!!! compat "Julia 1.6" + Specifying multiple collections to be appended requires at least Julia 1.6. # Examples ```jldoctest -julia> append!([1],[2,3]) +julia> append!([1], [2, 3]) 3-element Array{Int64,1}: 1 2 3 -julia> append!([1, 2, 3], [4, 5, 6]) +julia> append!([1, 2, 3], [4, 5], [6]) 6-element Array{Int64,1}: 1 2 @@ -983,6 +987,8 @@ end append!(a::AbstractVector, iter) = _append!(a, IteratorSize(iter), iter) push!(a::AbstractVector, iter...) = append!(a, iter) +append!(a::AbstractVector, iter...) = foldl(append!, iter, init=a) + function _append!(a, ::Union{HasLength,HasShape}, iter) n = length(a) i = lastindex(a) @@ -1001,17 +1007,32 @@ function _append!(a, ::IteratorSize, iter) end """ - prepend!(a::Vector, items) -> collection + prepend!(a::Vector, collections...) -> collection + +Insert the elements of each `collections` to the beginning of `a`. + +When `collections` specifies multiple collections, order is maintained: +elements of `collections[1]` will appear leftmost in `a`, and so on. -Insert the elements of `items` to the beginning of `a`. +!!! compat "Julia 1.6" + Specifying multiple collections to be prepended requires at least Julia 1.6. # Examples ```jldoctest -julia> prepend!([3],[1,2]) +julia> prepend!([3], [1, 2]) 3-element Array{Int64,1}: 1 2 3 + +julia> prepend!([6], [1, 2], [3, 4, 5]) +6-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 5 + 6 ``` """ function prepend! end @@ -1031,6 +1052,8 @@ end prepend!(a::Vector, iter) = _prepend!(a, IteratorSize(iter), iter) pushfirst!(a::Vector, iter...) = prepend!(a, iter) +prepend!(a::AbstractVector, iter...) = foldr((v, a) -> prepend!(a, v), iter, init=a) + function _prepend!(a, ::Union{HasLength,HasShape}, iter) require_one_based_indexing(a) n = length(iter) diff --git a/test/arrayops.jl b/test/arrayops.jl index 9ecd9f4a0bab2..98724b3ecc6d0 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -1576,6 +1576,14 @@ end @test append!([1,2], g) == [1,2] == push!([1,2], g...) @test prepend!([1,2], g) == [1,2] == pushfirst!([1,2], g...) + # multiple items + A = [1] + @test append!(A, [2, 3], [4], [5, 6]) === A + @test A == [1, 2, 3, 4, 5, 6] + A = [1] + @test prepend!(A, [2, 3], [4], [5, 6]) === A + @test A == [2, 3, 4, 5, 6, 1] + # offset array @test append!([1,2], OffsetArray([9,8], (-3,))) == [1,2,9,8] @test prepend!([1,2], OffsetArray([9,8], (-3,))) == [9,8,1,2]