Sum with Block

I'm aware that the documentation for AdditiveArithmetic even has the following example:

extension Sequence where Element: AdditiveArithmetic {
  func sum() -> Element {
    return reduce(.zero, +)
  }
}

But again, I think a sum() method, if provided by the Standard Library, should do better than that.

For example, using the above implementation:

let array1: [Float] = [ 3_000_000, -3_000_000,      0.125 ]
let array2: [Float] = [ 3_000_000,      0.125, -3_000_000 ]
let set = Set(array1)
print(array1.sum()) // 0.125
print(array2.sum()) // 0.0
print(set.sum()) // Either 0.0 or 0.125, it's different each time the program runs.

Why shouldn't sum() return 0.125 for all three of those cases?


It's easy to envision many more similar examples of where a reduce(0, +) hiding behind a sum() may result in surprising results, like trapping or not randomly between runs, etc.

reduce(0, +) says on the tin what it does, and unless you are unfamiliar with the specifics of the numeric type or operator, you will not be surprised.

sum() on the other hand, is IMO something that probably belongs in swift numerics or some other module.

From the other thread:

5 Likes