nha
nha

Reputation: 18005

Clojure expand reader macro

How can we find out what a reader macro does ?

For instance I know that a regex #"abc" is the same as (re-pattern "abc").

However the following : (macroexpand #"abc" ) yields #"abc", so how can I go from the reader special form to the "normal" function form ?

Upvotes: 3

Views: 381

Answers (1)

ClojureMostly
ClojureMostly

Reputation: 4713

You can find out what the reader expands to by using read-string:

(read-string "`(rest ~f)")
=>
(clojure.core/seq
 (clojure.core/concat (clojure.core/list (quote clojure.core/rest)) (clojure.core/list f)))
(read-string "#(x %&)")
=> (fn* [& rest__92046#] (x rest__92046#))
(read-string "`(~@x)")
=> (clojure.core/seq (clojure.core/concat x))
(read-string "`(~x)")
=> (clojure.core/seq (clojure.core/concat (clojure.core/list x)))
(read-string "'map")
=> (quote map)
(read-string "#'map")
=> (var map)
(read-string "@x")
=> (clojure.core/deref x)
(binding [*print-meta* true]
  (pr-str (read-string "(def ^:foo x 'map)")))
=> "(def ^{:foo true} x (quote map))"
(read-string "#\"x\"")
=> #"x"

In your particular case however: The regex is printed back to you the same way because that's how it's printed in clojure.

(class #"abc")
=> java.util.regex.Pattern

Upvotes: 3

Related Questions