We've already seen the function list that constructs a list out of several items. Here are some more functions for working with lists.
Returning the first element of a list: first
The function first returns the first element of a list:
> (first '(23 34 45))
There are similar functions second, third, and so on up to tenth for getting later items in a list.
Returning all but the first element of a list: rest
The function rest takes a list and returns the list minus the first element:
> (rest '(23 34 45))
Note that first and rest were traditionally called car and cdr; you can also use these alternative names.
Returning the nth element of a list: nth
The function nth takes a number and a list and returns the nth element of the list, counting the first element as zero:
> (nth 1 '(23 34 45))
Note that usually Lisp counts things starting from zero; the functions first and second are exceptions to this, so:
(nth 0 lst) is equivalent to (first lst)
and (nth 1 lst) is equivalent to (second lst).
Finding the length of a list: length
The function length returns the length of a list; for example:
> (length '(1 2 3)) 3
Constructing lists: cons
The function cons takes two parameters - an object and a list - and returns a new list with the object added to the front of the list. For example:
> (cons 1 '(2 3 4 5 6)) (1 2 3 4 5 6)
Note that the first object can itself be a list:
> (cons '(0 1) '(2 3 4 5 6))
((0 1) 2 3 4 5 6)
If the second parameter is not a list cons creates a dotted pair:
> (cons 'a 'b)
(a . b)
Joining lists: append
The function append takes any number of lists, and joins them all together into a single list. For example:
> (append '(1 3 5 7) '(2 4 6 8)) (1 3 5 7 2 4 6 8)
Reverse a list: reverse
The function reverse takes a list and reverses it:
> (reverse '(1 2 3 4)) (4 3 2 1)
Combining the list functions
Using these functions for manipulating lists, we can define a new function to perform just about any operation on lists that we need.
For example, let's define a function insert that inserts an item between the first and second items in a list. So:
> (insert 2 '(1 3 4 5 6))
(1 2 3 4 5 6)
We can do it as follows:
(defun insert (item lst) (cons (first lst) (cons item (rest lst))))
1. Swap the first two items in a list
Write a function swap to exchange the first two items of a list. Check that:
(swap '(9 8 7 6))
(8 9 7 6)
2. Duplicate the first item in a list
Write a function dup to duplicate the first item in a list, Check that:
(dup '(0 1 2 3))
(0 0 1 2 3)
3. Return a random item from a list
Write a function random-elt that returns a random element of a list. For example:
(random-elt '(11 22 33 44))
would randomly return one of the four numbers. Hint: use nth and random.
4. Return the last item in a list
Write a function last-elt which returns the last item in a list. For example:
(last-elt '(1 2 3 4))
should return 4.