Let's look a bit more closely at expressions.
In Lisp, + is a function, and an expression like (+ 2 3) is a function call. When Lisp evaluates a function call it performs the following two steps:
- It evaluates the arguments, left to right. In this case the arguments are just the numbers 2 and 3, and these evaluate to themselves.
- The values of the arguments are passed to the procedure, in this case +, which returns 5.
Let's look at a more complicated example: (/ (- 7 1) (- 4 2)). The sequence is:
- Evaluate (- 7 1) giving 6
- Evaluate (- 4 2) giving 2
- Evaluate (/ 6 2) giving 3
- Return 3
Preventing evaluation: quote
Nearly all operators behave like this, but there are some special operators, called special forms, that behave differently. One is quote. Try
> (quote (+ 2 3))
(+ 2 3)
The quote operator doesn't evaluate its argument - it simply returns it. It lets you tell Lisp to treat an expression as data, rather than something to be evaluated.
For convenience you can abbreviate (quote something) to 'something. Try:
> '(+ 2 3) (+ 2 3)
The ' operator allows you to protect an expression from evaluation. Now try quoting one of the arguments, as in:
> (list '(* 1 2) (* 3 4)) ((* 1 2) 12)
The quote stopped the first argument from being evaluated.
Evaluating expressions: eval
The opposite of quote is eval; it evaluates the expression passed as its argument. So:
> (eval '(+ 2 3)) 5
Things that evaluate to themselves
A number evaluates to itself, so you don't need to quote it:
> 12 12
Likewise nil, or the empty list, both evaluate to nil:
> () nil
1. Predict what the following Lisp expressions will give, and then check your answers by evaluating them:
(list (list 2 3) (list 4 5))
(list '(list 2 3) '(list 4 5))
'(list (list 2 3) (list 4 5))