JuliaLang/julia — pull request #6116 by stevengj (2014-03-11 15:01:30+00:00)
Title: more type-stable reductions

This patch tries to make reductions, especially `sum` and `prod`, as type-stable as is feasible (#6069). Key strategies:

* For reductions of two or more elements, always initialize the reduction variable as `v = op(A[1], A[2])` rather than as `v = A[1]`.
* For summation of empty collections, return `zero(T)+zero(T)` if `T` is known, rather than `zero(T)`. (Similarly for `prod` and `one`.)
* For summations of single-element collections, return `A[1] + zero(A[1])` rather than `A[1]`. (Similarly for `prod` and `one`.)

`sum` and `prod` of empty collections for which the eltype is *unknown* now throw an exception rather than returning `0` (which is the wrong answer for non-numeric collections).