The primitive function ``cons'' allows you to add a member to the front of a list. Here are two examples:
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.>(cons 1 nil) (1) >(cons 1 (cons 2 nil)) (1 2)
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:
What would happen? Well, the interpreter would say ``OK, cons I know, and I've got two arguments to evaluate. First, eval a.''>(cons a (b c d))
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