4.11 Quasiquoting: quasiquote and `

+Quasiquoting: quasiquote, unquote, and unquote-splicing in Reference: Racket also documents quasiquote.

The quasiquote form is similar to quote:

(quasiquote datum)

However, for each (unquote expr) that appears within the datum, the expr is evaluated to produce a value that takes the place of the unquote sub-form.

Example:

  > (quasiquote (1 2 (unquote (+ 1 2)) (unquote (- 5 1))))

  '(1 2 3 4)

The unquote-splicing form is similar to unquote, but its expr must produce a list, and the unquote-splicing form must appear in a context that produces either a list or a vector. As the name suggests, the resulting list is spliced into the context of its use.

Example:

  > (quasiquote (1 2 (unquote-splicing (list (+ 1 2) (- 5 1))) 5))

  '(1 2 3 4 5)

If a quasiquote form appears within an enclosing quasiquote form, then the inner quasiquote effectively cancels one layer of unquote and unquote-splicing forms, so that a second unquote or unquote-splicing is needed.

Example:

  > (quasiquote (1 2 (quasiquote (unquote (+ 1 2)
                                 (unquote (unquote (- 5 1)))))))

  '(1 2 (quasiquote (unquote (+ 1 2)) (unquote 4)))

The evaluation above will not actually print as shown. Instead, the shorthand form of quasiquote and unquote will be used: ` (i.e., a backquote) and , (i.e., a comma). The same shorthands can be used in expressions:

Example:

  > `(1 2 `(,(+ 1 2) ,,(- 5 1)))

  '(1 2 `(,(+ 1 2)  ,4))

The shorthand for of unquote-splicing is ,@:

Example:

  > `(1 2 ,@(list (+ 1 2) (- 5 1)))

  '(1 2 3 4)