Take the 2-minute tour ×

I'm learning lisp and have a question about a simple list:

(setq stuff '(one two three (+ 2 2)))
stuff ; prints "one two three (+ 2 2)"

(setq stuff (list `one `two `three (+ 2 2)))
stuff ; prints "one two three 4"

The first setq creates a list "one two three (+ 2 2)". The second list creates "one two three 4". Why does the first list not evaluate the (+ 2 2), but the second one does? I read in the Emacs Lisp intro documentation that when the list is built that it evaluates from the inside out. Why doesn't the first list evaluate the addition before adding it to the list?

This is elisp in emacs 24.

share|improve this question
add comment

2 Answers

up vote 8 down vote accepted

' is not equivalent to list, it's shorthand for quote. You're really doing this:

(setq stuff (quote (one two three (+ 2 2))))

The argument to quote is the expression (one two three (+ 2 2)).

From http://www.gnu.org/software/emacs/manual/html_node/elisp/Quoting.html: "The special form quote returns its single argument, as written, without evaluating it".

share|improve this answer
add comment

Looks like you're coming to grips with the evaluation semantics of Lisp, so keep playing around!

You can think of quote as suppressing evaluation of its argument. This allows you to write expressions that you can manipulate or pass around. It is also used to write data structures that should not be evaluated as function calls.

Data structures:

'(1 2 3)    ; => '(1 2 3)
(1 2 3)     ; => Lisp error: (invalid-function 1) 

;; The Lisp reader sees the number 1 in the function position and tries to call it, signalling an error.

Syntax transformations:

(setq x '(string-to-int "123"))
(setf (car x) 'string-to-list)
x                                   ; => '(string-to-list "123")

Delayed evaluation:

(setq x '(message "Hello World"))   ; => '(message "Hello World")
(eval x)                            ; => "Hello World"

There is a closely related special operator called syntax quote, written using the backtick. It allows you to evaluate individual forms in a quoted expression using the comma ( , ) operator. It is like quote with an escape hatch.

`(1 2 (+ 3 4))     ; => '(1 2 (+ 3 4))   
`(1 2 ,(+ 3 4))    ; => '(1 2 7)         ;; Note the comma!

Syntax quote also permits list splicing using the ,@ syntax:

`(1 2 ,@(+ 3 4))   ; => '(1 2 + 3 4)

As you can see, it splices the subsequent expression into the containing one. You probably won't see it all that often until you start writing macros.

list on the other hand is a simple function. It evaluates its arguments, then returns a new data structure containing these items.

 (list 1 2 (+ 3 4)) ; => '(1 2 7)
share|improve this answer
Very nice synopsis of everything list. This is the sort of thing one needs to read when one climbs out of the primordial customize syntax at the beginning of their Emacs use. –  Brady Trainor Mar 18 at 20:19
add comment

Your Answer


