# Sum with Block

**URL:** <https://forums.swift.org/t/sum-with-block/40785>\
**Category:** Pitches\
**Tags:** collection\
**Created:** [September 30, 2020, 5:29pm UTC](https://forums.swift.org/t/sum-with-block/40785 "2020-09-30T17:29:45Z")\
**Posts on this page:** 1\
**Showing post:** 22

<div class="post-metadata">

**Author:** ![Jens](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jens/32/12903_2.png) [@Jens](https://forums.swift.org/u/Jens)\
**Post date:** [October 1, 2020, 9:51am UTC](https://forums.swift.org/t/sum-with-block/40785/22 "2020-10-01T09:51:00Z")

</div>

I'm aware that [the documentation](https://developer.apple.com/documentation/swift/additivearithmetic) for `AdditiveArithmetic` even has the following example:

```swift
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:

```swift
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:

> [@Pitch: Method to sum numeric arrays](https://forums.swift.org/t/pitch-method-to-sum-numeric-arrays/24170/6):
>
> there are multiple related questions lurking here, which effect both floating-point and integer:
> 
> - Is the accumulation order specified? Is vectorization (which implicitly re-associates) allowed? Is the re-association allowed to be different depending on platform or runtime?
> - Is the accumulator width required to be the same as the element type? Can the compiler or runtime use a wider accumulator to prevent overflow? Is the compiler or runtime required to use a wider accumulator to prevent overflow?
> - Is the runtime required to produce a result as though computed in a single operation without intermediate overflow or rounding?

---

_[View the full topic](https://forums.swift.org/t/sum-with-block/40785)._
