31B. Example: Select the Even Members of a List

Sometimes you need more than two equations to define a function. This page introduces an example of that.

Let's write equations that define function evens(L), which yields a list of all members of list L that are even, preserving their order. For example, evens([2, 5, 6, 7, 9, 10]) = [2, 6, 10]. First, an obvious equation:

(evens.1)    evens([ ]) = [ ]

Now suppose that nonempty list L starts with an even number. Then that even number will be the first value in the result list, and it will be followed by all even numbers in tail(L).

(evens.2)    evens(L) = head(L) : evens(tail(L))   (when head(L) is even)

Finally, if L does not begin with an even number, just ignore that number; the answer is evens(tail(L)).

(evens.3)    evens(L) = evens(tail(L))   (when head(L) is odd)

Putting those three equations together gives an algorithm for evens(L).

  List evens(ConstList L)
  {
    if(L == NULL)
    {
      return NULL;
    }
    else {
      int       h = L->head;
      ConstList t = L->tail;
      if(h % 2 == 0)
      {
        return cons(h, evens(t));
      }
      else
      {
        return evens(t);
      }
    }
  }