`sum` syntax rule differs between Julia and `JuMP`

a = [1, 2, 3, 4]
sum(a[n] for n in 1:0) # ERROR: MethodError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer

using JuMP
m = Model()
@constraint(m, sum(a[n] for n in 1:0) >= 0) # It's OK.

Correct. In normal Julia you need to pass the init keyword:

julia> a = [1, 2, 3, 4]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> sum(a[n] for n in 1:0; init = 0)
0

We have this set by default in JuMP because we know that people really want 0.0 when they have an empty summation.

4 Likes

Thanks! Nice setting!

1 Like