1
作为后续行动,我previous question,我想写的是建立一个宏defprotocol
:集结协议的Clojure宏
(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 [email protected]
[email protected](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 [_]))
我对eval
并不满意。此外,map
表达式很丑陋。有没有更好的办法?欢迎任何和所有评论。
一旦我得到这个工作,我会去做一个类似的宏,为(build-reify ...)
。我正在编写一个相当大的Swing应用程序,它有几个组件(JButton
s,JCheckBox
es等),它们具有几乎相同的方法签名和操作。
有趣的想法。我必须去探索它。 – Ralph
例如,请参阅https://github.com/amalloy/ordered/blob/develop/src/deftype/delegate.clj - 我在周末写了这篇文章,并在今天早上进行了检查。它定义了一个新的'delegating-deftype'(在https://github.com/amalloy/ordered/blob/develop/src/ordered/map.clj处使用),这与我建议你“build -protocol'。 – amalloy
@Ralph我继续为你实施一个粗略的草稿,以便你明白我的意思:https://github.com/amalloy/build-protocol/blob/develop/src/build_protocol/core.clj – amalloy