Lists

As well as working with numbers, like 2 and 3, Lisp makes it easy to work with a group of several items, called a list. To specify a list of items you enclose the items in brackets. For example, the list of two-digit squares is:

(16 25 36 49 64 81)

A list containing no items is called the empty list. You can write it as:

()

but it is also called nil.

In fact we've already seen lists when we asked Lisp to evaluate:

(+ 2 3 4)

This was a list of four items: the symbol +, and the numbers 2, 3, and 4. When Lisp evaluates a list it treats the first item as the name of a procedure, and the remaining items as the arguments to the expression.

This illustrates one of the remarkable features of Lisp - Lisp programs and Lisp data are both expressed in the same way, as lists.

Building lists: list

The function called list allows us to build our own lists. Try:

> (list 1 2 3)
(1 2 3)

The function list builds a list of its arguments, enclosed in brackets. As with all functions, the arguments are evaluated first, so try:

> (list (* 1 2) (* 3 4))
(2 12)

The items in a list can themselves be lists. Try evaluating:

> (list (list 1 2) (list 3 4))
((1 2) (3 4))

This is a list of two items, each of which is itself a list of two items.

Exercises

1. Write an expression that will construct this list:

(1 (2 (3 4)))

Then try it out to check your answer.

2. Write an expression that will construct a list of two random numbers, each from 0 to 9.


Previous: Getting started

Next: Expressions