Scheme Programming/List Operations

Lists are a fundamental data structure in Scheme, as they are in many other functional languages. While among the simplest of structures, they have a rich set of operations and an amazing variety of uses. In this section, we'll cover the basics of creating and using lists.

Scheme Lists
A list is a sequence of elements ending with, sometimes called the "empty list" or "nil". We can build up lists with, which attaches a new element to the head of a list:

The first argument of  may be any Scheme object, and the second is a list; the value of  is a new list which contains  followed by the elements of. (Scheme's way of printing lists uses a shorthand which hides the final .  In the responses above, we simply see the elements of a list enclosed in parentheses.) It's important to note that we must always quote  , in order to prevent Scheme from trying to interpret it as an (invalid) expression.

Two predicates define the Scheme list type. , is true for  (the empty list) and is false otherwise, while returns true only for objects constructed with .

There are two basic functions for accessing the elements of lists. The first, , extracts the first element of a list:

Applying  to the empty list causes an error.

The second function,, gives us the tail of a list: that is, the list without its leading element:

As with, trying to apply   to the empty list causes an error.

The three functions,  , and   satisfy some useful identities. For any Scheme object x and list xs, we have

For any non-empty list ys, we also have

Clearly, building a list through successive  operations is clumsy. Scheme provides the built-in function  which returns a list of its arguments:

can take any number of arguments.

We can write a range of useful functions using just,  , and. For example, we can define a function to compute the length of a list:

This definition, like the definitions of most list operations, closely follows the recursive structure of a list. There is a case for the empty list (which is assigned the length 0), and a case for a non-empty list (the length of the tail of the list, plus one). In practice, Scheme provides as a built-in function.

Here's another simple example:

returns  if the argument n occurs in the list xs, and returns  otherwise. Once again, this definition follows the structure of the list argument. The empty list has no elements, so  is always false. If  is non-empty, then n could be the first element, or it could be somewhere in the tail. In the former case,  returns true immediately. In the latter, the return value should be true if n appears in and false otherwise. But since this is the definition of itself, we have a recursive call with the new argument.