Why does ^metadata 'symbol not work?

132 views Asked by At

The documentation on metadata claims that ^{:hi 10} 'x is equivalent to (with-meta 'x {:hi 10}), but I can't see that.

Evaluating the following on a repl,

(binding [*print-meta* true]
  (prn ^{:hi 10} 'x)
  (prn (with-meta 'x {:hi 10})))

prints the following, which shows that the first case doesn't get the metadata attached.

x
^{:hi 10} x

Am I doing something wrong?

1

There are 1 answers

0
Alex On BEST ANSWER

^ is a reader macro which attaches metadata to the form that follows it. However, 'x is not a form to which metadata can be applied; it expands to (quote x) via the ' reader macro. When you type ^{:hi 10} 'x, the metadata gets attached to the un-evaluated (quote x) form and not the bare symbol x:

user> (set! *print-meta* true)
user> (prn (read-string "'x"))
(quote x)
user> (prn (read-string "^{:hi 10} 'x"))
^{:hi 10} (quote x)

However, evaluating a form with metadata does not carry the metadata through to the result:

 user> (prn (eval (read-string "^{:hi 10} 'x")))
 x

You can attach metadata to a quoted symbol by placing the ^ after the ', as in:

user> (prn (read-string "'^{:hi 10} x"))
(quote ^{:hi 10} x)
user> (prn '^{:hi 10} x)
^{:hi 10} x