Processing a List as First Item and Remainder

A list computation can separate the first item from the rest and combine the first contribution with the result for the remainder.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Derive a count rule
  2. Account for copies
  3. Advance a position while preserving the original sequence
  4. Decide when a fold can remove the call stack

Derive a count rule

For blue, red, blue, count blue by adding one for the first item and recursing on red, blue. The empty remainder contributes zero. This uses a base case with a neutral result.

Account for copies

In Python, slicing the rest of a long list at each call creates additional lists. Passing a starting position instead avoids those suffix copies, while still introducing one call per step. See slice copying before choosing a representation for the remainder.[1]

Advance a position while preserving the original sequence

Addition over a list can use \(S(i)=a_i+S(i+1)\), ending at \(i=n\). Passing the same list and a changing position avoids constructing a new suffix list on every call. Python list slicing creates a new outer list, so this representation choice changes practical allocation behavior. See copying slices.

Input: [2, 9, 5]
S(3) = 0
S(2) = 5 + 0 = 5
S(1) = 9 + 5 = 14
S(0) = 2 + 14 = 16

Decide when a fold can remove the call stack

With an associative operation and identity, a loop may compute the same exact result. For subtraction, regrouping changes the answer. Test a non-associative combine rule if the abstraction advertises it, and make the direction of combination part of the interface.

References

  1. Jeff Erickson, Algorithms ↩