首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >build-protocol Clojure宏

build-protocol Clojure宏
EN

Stack Overflow用户
提问于 2011-06-20 21:30:15
回答 1查看 178关注 0票数 1

作为我的previous question的后续,我正在尝试编写一个构建defprotocol的宏

代码语言:javascript
运行
复制
(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"]))

应该扩展到

代码语言:javascript
运行
复制
(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 [_]))

我的尝试是:

代码语言:javascript
运行
复制
(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 '(...))

代码语言:javascript
运行
复制
(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应用程序,并且有几个组件(JButtonJCheckBoxes等)。它们具有几乎相同的方法签名和操作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-20 23:47:58

我觉得你做得颠倒了。首先指定"-method“内容,包装在某种容器中,以便构建协议知道是什么,并让它在宏内执行映射。例如:

代码语言:javascript
运行
复制
(build-protocol AProtocol
  {[this that whatever] [foo bar baz],
   [_] [hello goodbye]}
  ; a-method and b-method...
)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6411927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档