循环遍历宏的args

发布于 2024-12-02 19:51:38 字数 836 浏览 1 评论 0原文

我正在尝试在 Clojure 中编写一个宏,允许评估一系列简单的“def”表达式。说到宏,我是个菜鸟。这个想法是

(my-defs y1 1
     y2 "taco")

应该扩展到

(do (def y1 1) (def y2 "taco"))

以下代码对于两个 def 的特殊情况完成此操作

(defmacro my-defs 
  [& args]
  `(do
     (def ~(first args) ~(second args))
     (def ~(nth args 2) ~(nth args 3) )))

,这很好,但我很难概括这一点。我尝试了一些天真的事情,涉及循环 (partition 2 args) 元素的绑定,但我总是得到垃圾(我知道这不是很具体,但垃圾的多样性和范围似乎这里要报告的有点太多了)。我如何循环这些并评估我的定义?

聚苯乙烯 宏 my-defs 是一个玩具。我最终真正想要完成的是一个小助手宏来实例化一堆多方法实例。目前我有大块代码看起来

(defmethod f [A B] [x] "AB")
(defmethod f [A A] [x] "AA")
(defmethod f [C B] [x] "CB")

有点难看。如果我能做类似的事情就好了

(defmethods f
  [A B] [x] "AB"
  [A A] [x] "AA"
  [C B] [x] "CB")

I am trying to write a macro in Clojure that allows for evaluation of a series of simple "def" expressions. I am a n00b when it comes to macros. The idea is that

(my-defs y1 1
     y2 "taco")

should expand to

(do (def y1 1) (def y2 "taco"))

The following code accomplishes this for the special case of two defs

(defmacro my-defs 
  [& args]
  `(do
     (def ~(first args) ~(second args))
     (def ~(nth args 2) ~(nth args 3) )))

which is nice, but I am having trouble generalizing this. I tried out a few naive things involving looping through bindings of the elements of (partition 2 args) but I always got garbage (I know this isn't very specific but the diversity and extent of the garbage seemed a bit too much to report here). How do I loop over these are and evaluate my defs?

P.S.
The macro my-defs is a toy. What i really want to accomplish in the end is a littel helper macro to instantiate a bunch of multimethod instances. Currently I have large chunks of code that look like

(defmethod f [A B] [x] "AB")
(defmethod f [A A] [x] "AA")
(defmethod f [C B] [x] "CB")

which is a little unsightly. It would be nice if I could do something like

(defmethods f
  [A B] [x] "AB"
  [A A] [x] "AA"
  [C B] [x] "CB")

instead.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赢得她心 2024-12-09 19:51:38

在我看来,您正在寻找 ~@ 宏扩展/取消引用。

(defmacro defmethods [n & defs] 
   `(do ~@(map (fn [[a1 a2 a3]] 
                   `(def ~n ~a1 ~a2 ~a3)) 
               (partition 3 defs))))

It looks to me like you're looking for the ~@ macro expansion/unquote.

(defmacro defmethods [n & defs] 
   `(do ~@(map (fn [[a1 a2 a3]] 
                   `(def ~n ~a1 ~a2 ~a3)) 
               (partition 3 defs))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文