build-protocol Clojure macro
As a follow-up to my previous question, I am trying to write a macro that builds a 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"]))
should expand to
(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 [_]))
My attempt:
(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))))
and expansion (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 [开发者_运维知识库_]))
I'm not really happy about the eval
. Also, the map
expressions are pretty ugly. Is there a better way? Any and all comments welcome.
Once I get this working, I'm going to do a similar macro for (build-reify ...)
. I'm writing a rather large Swing application and have several components (JButton
s, JCheckBox
es, etc.) that have almost identical method signatures and actions.
I think you're doing it upside down. Specify the "-method" stuff first, wrapped in a container of some kind so build-protocol knows what's what, and let it do the map inside the macro. e.g:
(build-protocol AProtocol
{[this that whatever] [foo bar baz],
[_] [hello goodbye]}
; a-method and b-method...
)
精彩评论