4.11 Quasiquoting: quasiquote and ‘
Quasiquoting: quasiquote, unquote, and unquote-splicing in The Racket Reference 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: | ||
|
This form can be used to write functions that build lists according to certain patterns.
Examples: | ||||||||||
|
Or even to cheaply construct expressions programmatically. (Of course, 9 times out of 10, you should be using a macro to do this (the 10th time being when you’re working through a textbook like PLAI).)
Examples: | |||||||||||||||||||||||||||||
|
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: | ||
|
Using splicing we can revise the construction of our example expressions above to have just a single let expression and a single + expression.
Examples: | |||||||||||||||||||||||||||
|
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.
Examples: | ||||||
|
The evaluations 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: | ||
|
The shorthand form of unquote-splicing is ,@:
Example: | ||
|