(def x 1)
user=> '`~x
x
user=> `'~x
(quote 1)
Can anyone explain please how it is evaluated step by step?
The single-quote operator returns the expression or symbol that you are quoting without evaluating it. The syntax-quote operator returns the expression or symbol that you are quoting (with namespaces added), without evaluating it. The syntax-unquote operator "cancels out" the syntax-quote operator, so to speak, but not the single-quote. You can nest syntax-quotes and syntax-unquotes to perform weird and wonderful feats. My favorite analogy I read for understanding these is to consider syntax-quoting and syntax-unquoting as moving up and down rungs of a ladder (possible source).
In the form `x
, x
is syntax-quoted, so it isn't evaluated; instead, you get a namespaced symbol (like user/x
). But in the form `~x
, x
is syntax-unquoted again, so it is evaluated:
user=> `~x
1
On to your examples:
Example 1
'
is just sugar for (quote ...)
.
So '`~x
becomes (quote `~x)
. This in turn becomes (quote x)
(remember that `~
doesn't really do anything), which is why the whole expression evaluates to the symbol x
.
Example 2
In `'~x
, let's first replace the '
with quote
: `(quote ~x)
. The expression is syntax-quoted, so it won't be evaluated.
So you can think of the expression (quote ~x)
as an "intermediate step." But we're not done. x
inside the syntax-quote is syntax-unquoted, just as in my example up above. So even though this expression as a whole won't be evaluated, x
will be, and its value is 1
. In the end, you get the expression: (quote 1)
.
Blog post on the topic.
1
. – Chiron