31A. Example: Produce a Modified List

Suppose that squares(L) is intended to produce a list of the squares of the numbers in list L. For example,

   squares([2, 4, 6, 8] = [4, 16, 36, 64]
   squares([3, 2, 1]) = [9, 4, 1]
   squares([5]) = [25]
   squares([ ]) = [ ]

Every list is either empty or nonempty. The last example suggests an equation that defines squares([ ]).

(squares.1)    squares([ ]) = [ ]

What about nonempty lists? Break both the parameter list L and the answer list down into head and tail.

  1. Since squares([2, 3, 5, 6]) = [4, 9, 25, 36],

      head(squares([2, 3, 5, 6])) = 4 = 22.

    In general, whenever L is a nonempty list,

      (1)   head(squares(L)) = head(L)2

  2. Since squares([2, 3, 5, 6]) = [4, 9, 25, 36],

      tail(squares([2, 3, 5, 6])) = [9, 25, 36].

    But tail([2, 3, 5, 6]) = [3, 5, 6] and squares([3, 5, 6]) = [9, 25, 36], so

      tail(squares([2, 3, 5, 6])) = squares(tail(2, 3, 5, 6]))

    In general, whenever L is a nonempty list,

      (2)   tail(squares(L)) = squares(tail(L))

If you know that a list R has head h and tail t, then R must be h:t. That gives us our second equation for squares(L), which is used when L is not an empty list.

(squares.2)    squares(L) = head(L)2 : squares(tail(L))

It is straightforward to convert equations (squares.1) and (squares.2) into a C++ definition of squares.

  List squares(ConstList L)
  {
    if(L == emptyList) 
    {
      return emptyList;
    }
    else
    {
      const int h = head(L);
      return cons(h*h, squares(tail(L)));
    }
  }

Exercises

  1. Write equations for function sum(L), which yields the sum of all members of list L. For example, sum([2,3,4]) = 2 + 3 + 4 = 9. The sum of an empty list is 0. Make sure that your equations contain enough information to determine the value of sum(L) for any list of integers L. Answer

  2. Using your equations for sum(L) from the preceding question, do an evaluation of sum([3, 5, 7]) by only replacing expressions by equal expressions. Answer

  3. Following your equations, write a C++ definition of sum(L). Answer