Julia: cumsum(Union{}[]) results in an ambiguity error

Created on 22 Feb 2019  路  3Comments  路  Source: JuliaLang/julia

On Julia 1.1:

julia> cumsum(Union{}[])
ERROR: MethodError: Base.ArithmeticStyle(::Type{Union{}}) is ambiguous. Candidates:
  Base.ArithmeticStyle(::Type{#s72} where #s72<:Integer) in Base at traits.jl:21
  Base.ArithmeticStyle(::Type{#s623} where #s623<:Dates.AbstractTime) in Dates at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/Dates/src/types.jl:392
  Base.ArithmeticStyle(::Type{#s72} where #s72<:AbstractFloat) in Base at traits.jl:20
Possible fix, define
  Base.ArithmeticStyle(::Type{Union{}})
Stacktrace:
 [1] #cumsum!#581(::Int64, ::Function, ::Array{Union{},1}, ::Array{Union{},1}) at ./accumulate.jl:51
 [2] (::getfield(Base, Symbol("#kw##cumsum!")))(::NamedTuple{(:dims,),Tuple{Int64}}, ::typeof(cumsum!), ::Array{Union{},1}, ::Array{Union{},1}) at ./none:0
 [3] #cumsum#582(::Int64, ::Function, ::Array{Union{},1}) at ./accumulate.jl:91
 [4] (::getfield(Base, Symbol("#kw##cumsum")))(::NamedTuple{(:dims,),Tuple{Int64}}, ::typeof(cumsum), ::Array{Union{},1}) at ./none:0
 [5] cumsum(::Array{Union{},1}) at ./accumulate.jl:116
 [6] top-level scope at none:0

I got here from a special case of a function that takes the cumulative sum of the lengths of the entries in a NamedTuple, except the tuple was empty:

julia> [length(x) for x in NamedTuple()]
0-element Array{Union{},1}

Most helpful comment

Arguably, cumsum(Union{}[]) could return Union{}[]. We can infer +(Union{}, Union{}) as Union{}, so we know the element type, and we know the length. We cannot compute any element values, but luckily, we don't need any. That differs from sum(Union{}[]), where we do need one value.

All 3 comments

The error could certainly be improved, but what result would you expect other than an error? sum(Union{}[]) also throws. In your case, better do Int[length(x) for x in NamedTuple()].

Arguably, cumsum(Union{}[]) could return Union{}[]. We can infer +(Union{}, Union{}) as Union{}, so we know the element type, and we know the length. We cannot compute any element values, but luckily, we don't need any. That differs from sum(Union{}[]), where we do need one value.

Seems like an easy fix, no?

julia> @eval Base ArithmeticStyle(::Type{Union{}}) = ArithmeticUnknown()
Base.ArithmeticStyle

julia> cumsum(Union{}[])
0-element Array{Union{},1}
Was this page helpful?
0 / 5 - 0 ratings