作为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
s,JCheckBox
es等),它们具有几乎相同的方法签名和操作。
答案 0 :(得分:2)
我认为你是颠倒了。首先指定“-method”的东西,包装在某种容器中,这样build-protocol知道什么是什么,并让它在宏内部进行映射。 e.g:
(build-protocol AProtocol
{[this that whatever] [foo bar baz],
[_] [hello goodbye]}
; a-method and b-method...
)