From 38b85d9fb0be795f73c0bd0ab03c077d55cf6139 Mon Sep 17 00:00:00 2001 From: janEbert Date: Sun, 6 Oct 2019 14:11:22 +0200 Subject: [PATCH] Add `empty` for `AbstractArray`s and their types `empty` now works on all `AbstractArray`s and the corresponding call using `Type{<:AbstractArray}`. The method specialized on `AbstractVector` remains for inlining purposes. --- base/abstractarray.jl | 9 +++++++-- test/abstractarray.jl | 12 ++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 62547c8d7e01b..c281109c657c9 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -672,9 +672,10 @@ similar(::Type{T}, shape::Tuple{Union{Integer, OneTo}, Vararg{Union{Integer, One similar(::Type{T}, dims::Dims) where {T<:AbstractArray} = T(undef, dims) """ - empty(v::AbstractVector, [eltype]) + empty(a::AbstractArray, [eltype]) + empty(a::Type{AbstractArray}, [eltype]) -Create an empty vector similar to `v`, optionally changing the `eltype`. +Create an empty array similar to `a`, optionally changing the `eltype`. # Examples @@ -687,6 +688,10 @@ julia> empty([1.0, 2.0, 3.0], String) ``` """ empty(a::AbstractVector{T}, ::Type{U}=T) where {T,U} = Vector{U}() +function empty(a::Type{<:AbstractArray{T,N}}, ::Type{U}=T) where {T,N,U} + convert(AbstractArray{U}, a(undef, Tuple(Iterators.repeated(0,N)))) +end +empty(a::AbstractArray{T}, ::Type{U}=T) where {T,U} = empty(typeof(a), U) # like empty, but should return a mutable collection, a Vector by default emptymutable(a::AbstractVector{T}, ::Type{U}=T) where {T,U} = Vector{U}() diff --git a/test/abstractarray.jl b/test/abstractarray.jl index bf6c0f78a30ab..f40d129529837 100644 --- a/test/abstractarray.jl +++ b/test/abstractarray.jl @@ -892,11 +892,23 @@ end v = [1, 2, 3] v2 = empty(v) v3 = empty(v, Float64) + v4 = empty(typeof(v)) + v5 = empty(typeof(v), Float64) @test !isempty(v) empty!(v) @test isempty(v) @test isempty(v2::Vector{Int}) @test isempty(v3::Vector{Float64}) + @test isempty(v4::Vector{Int}) + @test isempty(v5::Vector{Float64}) + + m = [1 2; 3 4] + # These call `empty(typeof(m))`, so we don't test that case. + m2 = empty(m) + m3 = empty(m, Float64) + @test !isempty(m) + @test isempty(m2::Matrix{Int}) + @test isempty(m3::Matrix{Float64}) end @testset "CartesianIndices" begin