Accumulators in Loops
An accumulator stores a result for the part of the input a loop has processed so far.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Give it a neutral start
For a sum the neutral value is zero. Processing 4, 9, and minus 2 changes the running sum to 4, 13, and 11. You can state a loop invariant saying the accumulator equals the sum of all visited values.
Choose a safe initial value
For a maximum, starting at zero gives a false result on minus 4 and minus 2. Use a valid first element or an explicit missing state and specify the empty case. The distinction between absent and zero makes that empty case visible.[1]
Prove why the total represents exactly the prefix
Start at zero and add the next observation in order. With readings 6, minus 2, and 9, the state after the first two steps is four. The negative input still produces a legitimate sum. Before reading position \(i\), the accumulator is the sum of the \(i\) earlier values. The base case is the empty sum zero. Each step extends that prefix by one, so the value after the final iteration is the required total. Loop invariant preservation explains how to verify that step.
Decide what can be merged later
A sum from one batch and a sum from another can be added for exact integer arithmetic. A maximum needs a separate empty rule, and an average needs both the sum and count to merge chunks correctly. Choosing the current state from the final query avoids retaining unnecessary detail or discarding useful data.
Test inputs consisting of one value, a mix of positive and negative values, and an empty collection. For a maximum, include a list containing only negative values so an erroneous initial zero appears. See a running minimum for a selection problem with the same initialization concern.