From a3ef188430c7b9726cc7e90f36011d2f31c9e064 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Legat?= Date: Thu, 11 Jun 2020 16:41:08 +0200 Subject: [PATCH] Fix diagm_container for types without zero (#35743) --- stdlib/LinearAlgebra/src/dense.jl | 4 +++- stdlib/LinearAlgebra/test/dense.jl | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/stdlib/LinearAlgebra/src/dense.jl b/stdlib/LinearAlgebra/src/dense.jl index 8a57a1eaf52cf..4ea27e26bc7b8 100644 --- a/stdlib/LinearAlgebra/src/dense.jl +++ b/stdlib/LinearAlgebra/src/dense.jl @@ -301,7 +301,9 @@ function diagm_size(size::Tuple{Int,Int}, kv::Pair{<:Integer,<:AbstractVector}.. end function diagm_container(size, kv::Pair{<:Integer,<:AbstractVector}...) T = promote_type(map(x -> eltype(x.second), kv)...) - return zeros(T, diagm_size(size, kv...)...) + # For some type `T`, `zero(T)` is not a `T` and `zeros(T, ...)` fails. + U = promote_type(T, typeof(zero(T))) + return zeros(U, diagm_size(size, kv...)...) end diagm_container(size, kv::Pair{<:Integer,<:BitVector}...) = falses(diagm_size(size, kv...)...) diff --git a/stdlib/LinearAlgebra/test/dense.jl b/stdlib/LinearAlgebra/test/dense.jl index 1c7eeb5b4acac..2dec8e95402d7 100644 --- a/stdlib/LinearAlgebra/test/dense.jl +++ b/stdlib/LinearAlgebra/test/dense.jl @@ -939,4 +939,15 @@ end @test exp(log(A2)) ≈ A2 end +struct TypeWithoutZero end +Base.zero(::Type{TypeWithoutZero}) = TypeWithZero() +struct TypeWithZero end +Base.promote_rule(::Type{TypeWithoutZero}, ::Type{TypeWithZero}) = TypeWithZero +Base.zero(::Type{<:Union{TypeWithoutZero, TypeWithZero}}) = TypeWithZero() +Base.:+(x::TypeWithZero, ::TypeWithoutZero) = x + +@testset "diagm for type with no zero" begin + @test diagm(0 => [TypeWithoutZero()]) isa Matrix{TypeWithZero} +end + end # module TestDense