From ca95b73ba192cc9952b1c36f7de6ac5691df89d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Legat?= Date: Tue, 5 May 2020 12:29:52 +0200 Subject: [PATCH] Fix diagm_container for types without zero --- 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 cf6af00481060..7e5eb8e9cdd8a 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 3305a9284343b..bcba570946163 100644 --- a/stdlib/LinearAlgebra/test/dense.jl +++ b/stdlib/LinearAlgebra/test/dense.jl @@ -928,4 +928,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