Lisp tutorial 1: Expressions

The running of a Lisp program is in some ways like the evaluation of formulae in a spreadsheet. Lisp calls its formulae "expressions".

There are several kinds of expressions. The simplest ones are literal values, that is, when you evaluate the expression, you get the same expression back from the evaluator.

Numbers and strings are common literal expressions. Numbers are written in the ordinary way. Strings are written between double-quote characters, "like this". If you need to put a double-quote character inside a string, precede it with a backslash.

The next sort of expression is called a symbol. Most symbols look like words, perhaps hyphenated. In fact, most sequences of characters that don't contain any spaces, other than strings, numbers or things with brackets in them, can be used as symbols. Examples of symbols are things like:

Two common uses of symbols are to name values, and to name functions (parts of programs). So, for example, the name screen-width refers to a function that checks how many columns wide your screen is, and returns that as a number. In maths you will have just used one-character symbols like x and y, but in Lisp you can have any length of symbol.

If you want to refer to a symbol itself, rather than the thing it names, you precede it with a single-quote mark. This may sound obscure, but it'll turn out to be important later.

The other main kind of expression is the list. A list is a sequence of expressions, with brackets around the whole lot. For example, (a b c) is a list of three items. You can have lists within lists, such as (a (1 2) b c) which is a list of four items, the second of which is a list of two items.

Lisp uses lists to represent its formulae. For example, to write what in spreadsheets and other languages would be 1+2, in Lisp you write (+ 1 2). If you wanted to multiply z by 2, and subtract 1 from that, you would write (- (* z 2) 1).

If you want a list itself, rather than using it as a formula for calculation, you precede it with a single-quote character. For example, (+ 1 2) evaluates to 3, but '(+ 1 2) evaluates to a list of three elements, of which the first is the symbol +, and the other elements are the numbers 1 and 2. Likewise, the expression (length '(a b c d e f)) evaluates to 6 -- it is the length of the inner list.

[lisp] [computing]
John C. G. Sturdy
[John's home] Last modified: Thu Nov 1 14:56:57 GMT 2007