Skip to content

Commit

Permalink
Specialize haszero for Union{Missing,<:Number} (#56169)
Browse files Browse the repository at this point in the history
Since `zero(::Union{Missing,T})` calls `zero(T)` internally, we may use
the same logic for `LinearAlgebra.haszero`. This helps with certain
structured matrix operations:
```julia
julia> M = Matrix{Union{Int,Missing}}(missing,2,2)
2×2 Matrix{Union{Missing, Int64}}:
 missing  missing
 missing  missing

julia> triu(M)
2×2 Matrix{Union{Missing, Int64}}:
  missing  missing
 0         missing
```
whereas previously, this would have been
```julia
julia> triu(M)
2×2 Matrix{Union{Missing, Int64}}:
 missing  missing
 missing  missing
```
  • Loading branch information
jishnub authored Oct 21, 2024
1 parent 8bdacc3 commit 82e0e28
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
1 change: 1 addition & 0 deletions stdlib/LinearAlgebra/src/dense.jl
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ norm2(x::Union{Array{T},StridedVector{T}}) where {T<:BlasFloat} =
# Conservative assessment of types that have zero(T) defined for themselves
haszero(::Type) = false
haszero(::Type{T}) where {T<:Number} = isconcretetype(T)
haszero(::Type{Union{Missing,T}}) where {T<:Number} = haszero(T)
@propagate_inbounds _zero(M::AbstractArray{T}, inds...) where {T} = haszero(T) ? zero(T) : zero(M[inds...])

"""
Expand Down
8 changes: 8 additions & 0 deletions stdlib/LinearAlgebra/test/triangular.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,14 @@ end
@test istril(U, k) == istril(A, k)
end
end

@testset "Union eltype" begin
M = Matrix{Union{Int,Missing}}(missing,2,2)
U = triu(M)
@test iszero(U[2,1])
U = tril(M)
@test iszero(U[1,2])
end
end

@testset "indexing with a BandIndex" begin
Expand Down

0 comments on commit 82e0e28

Please sign in to comment.