next up previous
Next: Quote Up: Some Primitive Functions Previous: Some Primitive Functions

Constructors: Cons, List, and Append

The primitive function ``cons'' allows you to add a member to the front of a list. Here are two examples:

>(cons 1 nil)
(1)
>(cons 1 (cons 2 nil))
(1 2)
It is worth looking at what is going on in these examples. In the first, cons is given two arguments. The first is 1 and the second is nil, which, you will remember, is the same as (). So, cons takes the first argument and inserts it as the first element of the second.

To understand the second example, it is useful to anthropomorphize the interpreter. It says, ``OK, cons is a function I know and I've got two arguments to that function, 1 and (cons 2 nil). The first argument is an atom, but a special one, and evaluates to 1. The second is a list, so its first element names a function, i.e. cons, and there are two arguments to that function, 2 and nil. 2 evaluates to 2, and nil evaluates to nil (the empty list). So, putting 2 into the empty list we get (2). Now I know what the second argument to the first cons is, we can go ahead and insert the first argument, i.e. 1. Hence we get (1 2).''

Now we discuss what happens when we deal with atoms that are not special. Suppose you wanted to construct the list (a b c d) and you try to do this by saying:

>(cons a (b c d))
What would happen? Well, the interpreter would say ``OK, cons I know, and I've got two arguments to evaluate. First, eval a.''

Immediately you get an error because (we are assuming) a is an unbound variable (you haven't set it to anything). How do you fix this problem?



©Colin Allen & Maneesh Dhagat
April 1997