The Accumulator PatternΒΆ
In the previous example, we wrote a function that computes the square of a number.
In this section we will reimplement the square function and use a different algorithm, one that relies on addition instead of multiplication.
If you want to multiply two numbers together, the most basic approach is to think of it as repeating the process of adding one number to itself.
- This is a great example of “black box” design.
- We can change out the details inside of the box and still use the function exactly as we did before.
This pattern of iterating the updating of a variable is commonly referred to as the accumulator pattern.
Here is the same program in codelens. Step through the function and watch the “running total” accumulate the result.