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