12

I have this macro, which rewrites define. If I remove the " ` " backtick it won't work. What is the explanation?

(defmacro define ((name &rest r) body) 
  `(defun ,name ,r ,body))
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
Alex
  • 357
  • 2
  • 15

2 Answers2

23

A single quote followed by the written representation of a value will produce that value:

Example: '(1 x "foo") will produce a value that prints as (1 x "foo").

Suppose now that I don't want a literal symbol x in the list. I have a variable x in my program, and I want to insert the value to which x is bound.

To mark that I want the value of x rather than the symbol x, I insert a comma before x:

'(1 ,x "foo")

It won't work as-is though - I now get a value that has a literal comma as well as a symbol x. The problem is that quote does not know about the comma convention.

Backtick or backquote knows about the comma-convention, so that will give the correct result:

> `(1 ,x "foo")
(1 3 "foo")          ; if the value of x is 3

Read more here: http://www.lispworks.com/documentation/HyperSpec/Body/02_df.htm

soegaard
  • 30,661
  • 4
  • 57
  • 106
  • Great, I got it, thanks. One more thing. What does that & operator before rest do? (&rest) – Alex May 10 '15 at 10:32
  • 3
    The `&rest` allows you to define functions that have a variable amount of arguments. Say you want to define a plus function where both (plus 2 3) and (plus 2 3 4) works. This page has a nice explanation: http://www.gigamonkeys.com/book/functions.html – soegaard May 10 '15 at 10:35
  • 2
    I think it's worth noting that this feature is called **quasiquoting** or **quasi-quoting**. – Frank Tan Oct 26 '16 at 00:25
7

The backtick/backquote disables evaluation for every subexpression not preceded by a comma for the list that follows the operator.

From the common lisp cookbook, explanation and a few examples.

uraimo
  • 19,081
  • 8
  • 48
  • 55