Inconsistency in `sum` of an empty generator

I see. The iter field of a generator is the iter in the following expression:

g = (f(x) for x in iter)

A generator has two fields, f and iter. It appears that there is a specialization for the case when f == identity:

julia> sum(x for x in Int[])
0

julia> sum(2x for x in Int[])
ERROR: MethodError: reducing over an empty collection is not
allowed; consider supplying `init` to the reducer

I guess it makes sense, because the generator (x for x in iter) should be exactly the same as just iterating through iter.

This explains why g1 doesn’t work: It’s because x -> 1 is not the identity function. sum will throw an error when f is not the identity function because the return type of f might be different from the element type of iter.

3 Likes