Sub topic 9
Carrying State in an Accumulator
This chapter assumes you can write a basic recursive function with a base case and a recursive case, and that you know how each call gets its own stack frame. It introduces accumulator-passing style, a way of writing recursion that the next two chapters build on.
The problem: work left waiting
Look at a plain recursive sum over a list:
def sum_list(items):
if not items:
return 0
return items[0] + sum_list(items[1:])
print(sum_list([3, 1, 4])) # 8The addition items[0] + ... cannot run until the recursive call returns. Each frame therefore holds a pending operation. The real arithmetic only happens while the stack unwinds, starting from the deepest frame.
The idea: pass the partial result forward
An accumulator is an extra parameter that holds the result computed so far. Each call does its share of the work before it recurses and passes the updated value down. When the base case is reached, the answer is already complete, so the base case returns the accumulator.
def sum_list_acc(items, acc=0):
if not items:
return acc
return sum_list_acc(items[1:], acc + items[0])
print(sum_list_acc([3, 1, 4])) # 8The recursive call is now the last thing the function does. No frame has work left to do after its call returns.
| Step | Plain version state | Accumulator version state |
|---|---|---|
| Going down | pending `3 +`, `1 +`, `4 +` | acc = 0, 3, 4, 8 |
| Base case returns | 0 | 8 |
| Coming back up | additions performed | value passed through unchanged |
Order can change
The accumulator combines values in a different order from the plain version. For addition this makes no difference. For building a list it does, and you can sometimes use that on purpose. Prepending each element to the accumulator reverses a list:
def reverse_acc(items, acc=()):
if not items:
return list(acc)
return reverse_acc(items[1:], (items[0],) + acc)
print(reverse_acc([1, 2, 3])) # [3, 2, 1]If you need the original order, append instead of prepend. Another option is to accumulate in reverse and flip the result once at the end.
Hiding the accumulator
Callers should not need to know about acc. A default argument works for immutable starting values. You can also use a small wrapper:
def count_positive(items):
def go(rest, acc):
if not rest:
return acc
return go(rest[1:], acc + (1 if rest[0] > 0 else 0))
return go(items, 0)
print(count_positive([5, -2, 7, 0])) # 2Common errors
- Returning the identity in the base case. Writing
return 0instead ofreturn accthrows away all the work done. - Wrong starting value. The starting value must be the identity of the operation: 0 for sums, 1 for products, an empty sequence for building a list.
- Mutable default accumulators.
def f(items, acc=[])shares one list across every call tof. Use a tuple,Nonewith a check, or a wrapper. - Mixing styles.
return items[0] + f(items[1:], acc)uses an accumulator and still leaves work pending, so it gains nothing.
Exercise
Write product_acc(items, acc=?), an accumulator-style function that multiplies the numbers in a list. What must the default value of acc be, and what does product_acc([]) return?
Show answer
The default must be 1, the multiplicative identity: def product_acc(items, acc=1): return acc if not items else product_acc(items[1:], acc * items[0]). Calling product_acc([]) returns 1.
Exercise
In sum_list_acc([2, 5]), what values does acc take across the calls, and how many additions run after the base case returns?
Show answer
acc takes the values 0, then 2, then 7. No additions run after the base case, which returns 7 directly.