Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ^metadata 'symbol not work?

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?

like image 753
Malabarba Avatar asked Jun 18 '15 17:06

Malabarba


1 Answers

^ 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
like image 153
Alex Avatar answered Nov 10 '22 15:11

Alex