Inconsistency between zero(x) and zero(T::Type) for matrices

I was experimenting with function sum and found out that it does not work for empty collections of matrices, Julia 1.7.2. The reason is there is no method zero(::Type{Array{T,N}}), thus you must specify init manually. However, there is a method zero(::Array{T,N}). As a consequence zero([1 2; 3 4]) works but zero(Matrix{Int}) does not work. Maybe there is a reason for this, but for me it seems to be very unintuitive. Similar thing happens for function one and consequently prod.

What would zero(Matrix{Float64}) return? I guess you could have a lazy representation that doesn’t actually have a definite size, but that’s very different from what the other version does, be wise the input object has a size.

1 Like

But what should this call return?

Maybe 0*LinearAlgebra.I? Be aware that this cannot be mutated/updated, though.

There is a family of initial-value issues

The basic reason is that the size of the matrix is not encoded in the type. (If you use an SMatrix it works fine, in contrast, because StaticArrays include the size in the type.)

4 Likes

It’s also not of the type you asked for.

1 Like

A, yes, this is unfortunate. It skipped my mind this is the case. I guess there is no good fix then. Functions sum and prod becoming type unstable would be even worse.