2011-06-20 67 views
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等),它们具有几乎相同的方法签名和操作。

回答

2

我认为你是在颠倒。首先指定“-method”的东西,包装在某种容器中,这样build-protocol就知道是什么东西,并让它在宏内执行映射。例如:

(build-protocol AProtocol 
    {[this that whatever] [foo bar baz], 
    [_] [hello goodbye]} 
    ; a-method and b-method... 
) 
+0

有趣的想法。我必须去探索它。 – Ralph

+0

例如,请参阅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

+0

@Ralph我继续为你实施一个粗略的草稿,以便你明白我的意思:https://github.com/amalloy/build-protocol/blob/develop/src/build_protocol/core.clj – amalloy