Should empty sum (and product) be defined?

julia> sum([1 2])
3

julia> sum([]) # from math = 0 "by convention"
ERROR: MethodError: no method matching zero(::Type{Any})
Closest candidates are:
  zero(::Type{Base.LibGit2.Oid}) at libgit2/oid.jl:88
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuildItem}) at pkg/resolve/versionweight.jl:80
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuild}) at pkg/resolve/versionweight.jl:120
  ...
 in _mapreduce(::Base.#identity, ::Base.#+, ::Base.LinearFast, ::Array{Any,1}) at ./reduce.jl:148
 in sum(::Array{Any,1}) at ./reduce.jl:229

julia> sum((1, 2))
3

julia> sum((1,))
1

julia> sum((,))
ERROR: syntax: unexpected ,

julia> sum(())
ERROR: StackOverflowError:
 in convert(::Type{Union{}}, ::Int64) at ./sysimg.jl:55 (repeats 80000 times)

I can see that maybe you want an error. Just not sure.

Not sure how you do the product, but it is defined as 1.

This has already been discussed, see https://github.com/JuliaLang/julia/issues/8092.

Note that

julia> sum(Int[])
0

Edit: The stackoverflow is probably a bug.

1 Like

Note that

julia> sum(Int[])
0

I.e. it works when it is able to determine the type of the empty array.

1 Like