循环遍历宏的args
我正在尝试在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,您正在寻找 ~@ 宏扩展/取消引用。
It looks to me like you're looking for the ~@ macro expansion/unquote.