作为我的previous question的后续,我正在尝试编写一个构建defprotocol的宏
(build-protocol AProtocol
  [(a-method [this]) (b-method [this that])]
  (map (fn [name] `(~(symbol (str name "-method")) [~'this ~'that ~'the-other]))
    ["foo" "bar" "baz"])
  (map (fn [name] `(~(symbol (str name "-method")) [~'_]))
    ["hello" "goodbye"]))应该扩展到
(defprotocol AProtocol
  (a-method [this])
  (b-method [this that])
  (foo-method [this that the-other])
  (bar-method [this that the-other])
  (baz-method [this that the-other])
  (hello-fn [_])
  (goodbye-fn [_]))我的尝试是:
(defmacro build-protocol [name simple & complex]
  `(defprotocol ~name ~@simple
     ~@(loop [complex complex ret []]
         (if (seq complex)
           (recur (rest complex) (into ret (eval (first complex))))
           ret))))和扩展(macroexpand-1 '(...))
(clojure.core/defprotocol AProtocol
  (a-method [this])
  (b-method [this that])
  (foo-method [this that the-other])
  (bar-method [this that the-other])
  (baz-method [this that the-other])
  (hello-method [_])
  (goodbye-method [_]))我对eval并不是很满意。而且,map表达式相当难看。有没有更好的方法?欢迎任何评论。
一旦我让它正常工作,我将为(build-reify ...)做一个类似的宏。我正在编写一个相当大的Swing应用程序,并且有几个组件(JButton、JCheckBoxes等)。它们具有几乎相同的方法签名和操作。
发布于 2011-06-20 23:47:58
我觉得你做得颠倒了。首先指定"-method“内容,包装在某种容器中,以便构建协议知道是什么,并让它在宏内执行映射。例如:
(build-protocol AProtocol
  {[this that whatever] [foo bar baz],
   [_] [hello goodbye]}
  ; a-method and b-method...
)https://stackoverflow.com/questions/6411927
复制相似问题