Skip to content

Commit

Permalink
Fix diagm_container for types without zero (#35743)
Browse files Browse the repository at this point in the history
  • Loading branch information
blegat authored Jun 11, 2020
1 parent f0b369c commit a3ef188
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion stdlib/LinearAlgebra/src/dense.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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...)...)
Expand Down
11 changes: 11 additions & 0 deletions stdlib/LinearAlgebra/test/dense.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit a3ef188

Please sign in to comment.