Clojure - How to make my macro expand before system macros?

前端 未结 3 429
我在风中等你
我在风中等你 2021-01-12 06:57

If I do, for example:

(defmacro qqq [] \'(toString [this] \"Qqq\"))
(reify Object (qqq))

it fails because of reify sees

相关标签:
3条回答
  • 2021-01-12 06:59

    The macro that forces given user macros to expand first (requires clojure.walk):

    (defmacro expand-first [the-set & code] 
     `(do ~@(prewalk 
      #(if (and (list? %) (contains? the-set (first %)))
      (macroexpand-all %)
      %) code)))
    

    Who has ideas how to make it better?

    0 讨论(0)
  • 2021-01-12 07:00

    This will work:

    (defn reifyx [x y]
      (eval `(reify ~x ~y)))
    
    (defn qqq [] '(toString [this] "Qqq"))
    
    (reifyx 'Object (qqq))
    

    I found an apply-macro. I tried it, but it seems to be broken. The most important thing I gleaned from looking at apply-macro was that it solved the problem using eval just as I have.

    0 讨论(0)
  • 2021-01-12 07:22

    There is a reader-macro to evaluate things at read-time (before macro-expansion time)..

    (defn qqq [] '(toString [this] "Qqq"))
    (reify Object #=(qqq))
    

    I've never seen this done in "real" code, and I think most people would consider it a hack, but it's there if you need it.

    0 讨论(0)
提交回复
热议问题