32B. Example: Sum of the Numbers in a List

Suppose sum(L) is intended to return the sum of all of the numbers in linked list L. A scan algorithm will do the job. Here is a plan showing the values of variables p and s for computing sum(L) for L = [2, 4, 6, 8].

 p      s 
[2, 4, 6, 8]    0
[4, 6, 8]    2
[6, 8]    6
[8]    12
[ ]    20

Again there is a loop invariant: at each line, equation

(sum-invariant)   s + sum(p) = sum(L).

is true. So, when p is an empty list (and sum(p) = 0), s must equal sum(L). Here is a definition of sum in C++.

  int sum(ConstList L)
  {
    ConstList p = L;
    int       s = 0;

    while(!isEmpty(p))
    {
      s += head(p);
      p  = tail(p);
    }
    return s;
  }
Using a for-loop shortens it.
  int sum(ConstList L)
  {
    int s = 0;
    for(ConstList p = L; p != NULL; p = p->tail)
    {
      s += p->head;
    }
    return s;
  }