使用宏动态生成reify子句

时间:2019-06-11 00:23:53

标签: clojure reify

我正在尝试包装实现,并为被包装对象实现的所有接口动态生成reify子句。

例如:

我想生成:

(reify
  BaseInterface
    (fee [_] (custom-operation wrapped))
    (foo [_] (.foo wrapped)))

(reify
  BaseInterface
    (fee [_] (custom-operation wrapped))
    (foo [_] (.foo wrapped))
  AnotherInterface
    (bar [_] (.bar wrapped)))

取决于wrapped是仅实现BaseInterface还是同时实现BaseInterfaceAnotherInterface

我尝试了类似以下的操作,但是由于在编译时对宏进行了评估并且我的第二个参数(cond->表达式)没有运行时值,所以它失败了:

(defmacro add-interface-implementations
  "Adds additional interface implementations to a reify expression.
   This is useful to create a reify expression dynamically without introducing if-else branching."
  [reify-expr interface->methods]
  (reduce
    (fn [expr# entry#]
      (println "expr#" expr#)
      (println "entry#" entry#)
      (let [[interface# body#] entry#]
        (cons
          (first expr#)
          (cons interface#
                (reduce
                  (fn [e# m#]
                    (cons m# e#))
                  (rest expr#)
                  body#)))))
    reify-expr
    interface->methods))

(add-interface-implementations
  (reify
    BaseInterface
      (fee [_] (custom-operation wrapped))
      (foo [_] (.foo wrapped)))
  (cond-> {}
    (instance? AnotherInterface foo)
    (assoc AnotherInterface [(bar [_] (.bar wrapped))])))

关于如何实现我正在尝试的任何建议。我想避免if-else分支,因为一旦我拥有更多接口,它就会导致组合爆炸。

0 个答案:

没有答案