next up previous
Contents Next: Changing Variable Values Up: Some Primitive Functions Previous: Quote

Selectors: First and Rest

There are two primitive list selectors. Historically, these were known as car and cdr, but these names were hard to explain since they referred to the contents of various hardware registers in computers running Lisp. In Common Lisp the functions have been given alternative names, first and rest, respectively. (You can still use the old names in Common Lisp. One of us learned Lisp in the old days, so occasionally we'll use car or cdr instead of first or rest.)

First takes a list as an argument and returns the first element of that list. It works like this:

> (first '(a s d f))
> (first '((a s) d f))
(a s)
Rest takes a list as an argument and returns the list, minus its first element.

> (rest '(a s d f))
(s d f)
> (rest '((a s) d f))
(d f)
> (rest '((a s) (d f)))
((d f))
You can use setq to save yourself some typing. Do the following:

> (setq a '(a s d f))
(a s d f)
You can now use a instead of repeating the list (a s d f) every time. So:

> (first a) 
> (rest a)
(s d f)
> (first (rest a))
You can figure out the rest, like how to get at the third and fourth elements of the list using first and rest.

© Colin Allen & Maneesh Dhagat
March 2007