2.20 Quasiquoting: quasiquote, unquote, and unquote-splicing
Quasiquoting: quasiquote and ` in Guide: Racket introduces quasiquote.
(quasiquote datum) |
Examples: |
> (quasiquote (0 1 2)) |
'(0 1 2) |
> (quasiquote (0 (unquote (+ 1 2)) 4)) |
'(0 3 4) |
> (quasiquote (0 (unquote-splicing (list 1 2)) 4)) |
'(0 1 2 4) |
> (quasiquote (0 (unquote-splicing 1) 4)) |
unquote-splicing: expected argument of type <proper list>; |
given 1 |
> (quasiquote (0 (unquote-splicing 1))) |
'(0 . 1) |
A quasiquote, unquote, or unquote-splicing form is typically abbreviated with `, ,, or ,@, respectively. See also Reading Quotes.
Examples: |
> `(0 1 2) |
'(0 1 2) |
> `(1 ,(+ 1 2) 4) |
'(1 3 4) |
> `#s(stuff 1 ,(+ 1 2) 4) |
'#s(stuff 1 3 4) |
> `#hash(("a" . ,(+ 1 2))) |
'#hash(("a" . 3)) |
> `#hash((,(+ 1 2) . "a")) |
'#hash((,'(+ 1 2) . "a")) |
> `(1 ,@(list 1 2) 4) |
'(1 1 2 4) |
> `#(1 ,@(list 1 2) 4) |
'#(1 1 2 4) |
A quasiquote form within the original datum increments the level of quasiquotation: within the quasiquote form, each unquote or unquote-splicing is preserved, but a further nested unquote or unquote-splicing escapes. Multiple nestings of quasiquote require multiple nestings of unquote or unquote-splicing to escape.
Examples: |
> `(1 `,(+ 1 ,(+ 2 3)) 4) |
'(1 `,(+ 1 5) 4) |
> `(1 ```,,@,,@(list (+ 1 2)) 4) |
'(1 ```,,@,3 4) |
The quasiquote form allocates only as many fresh cons cells, vectors, and boxes as are needed without analyzing unquote and unquote-splicing expressions. For example, in
`(,1 2 3)
a single tail '(2 3) is used for every evaluation of the quasiquote expression.