From fc6c618c4e199330429c05836eeb779723e7c97b Mon Sep 17 00:00:00 2001 From: Frames White Date: Sun, 10 Mar 2024 02:36:14 +0800 Subject: [PATCH] Handle zero on arrays of unions of number types and missings (#53602) --- base/abstractarray.jl | 1 + test/abstractarray.jl | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/base/abstractarray.jl b/base/abstractarray.jl index a9431197932dd..9042e5f81e462 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -1218,6 +1218,7 @@ end copymutable(itr) = collect(itr) zero(x::AbstractArray{T}) where {T<:Number} = fill!(similar(x, typeof(zero(T))), zero(T)) +zero(x::AbstractArray{S}) where {S<:Union{Missing, Number}} = fill!(similar(x, typeof(zero(S))), zero(S)) zero(x::AbstractArray) = map(zero, x) ## iteration support for arrays by iterating over `eachindex` in the array ## diff --git a/test/abstractarray.jl b/test/abstractarray.jl index 9d9c9b9c87776..1411864acfa03 100644 --- a/test/abstractarray.jl +++ b/test/abstractarray.jl @@ -1972,6 +1972,16 @@ end @test zero([[2,2], [3,3,3]]) isa Vector{Vector{Int}} @test zero([[2,2], [3,3,3]]) == [[0,0], [0, 0, 0]] + + + @test zero(Union{Float64, Missing}[missing]) == [0.0] + struct CustomNumber <: Number + val::Float64 + end + Base.zero(::Type{CustomNumber}) = CustomNumber(0.0) + @test zero([CustomNumber(5.0)]) == [CustomNumber(0.0)] + @test zero(Union{CustomNumber, Missing}[missing]) == [CustomNumber(0.0)] + @test zero(Vector{Union{CustomNumber, Missing}}(undef, 1)) == [CustomNumber(0.0)] end @testset "`_prechecked_iterate` optimization" begin