问题传递一个矢量作为绑定到宏 [英] Problem with passing a vector as a binding to the for macro

查看:167
本文介绍了问题传递一个矢量作为绑定到宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想使用宏来处理列表任意数量。我想创建传递一个矢量的函数的结合,因为列表的数目而变化。

I have an arbitrary number of lists which I would like to process using the for macro. I want to create a function that passes a vector as the binding since the number of lists varies.

如果我硬code的结合,它的工作原理如我所料:

If I hard code the binding, it works as I expect:

=> (def list1 '("pink" "green"))
=> (def list2 '("dog" "cat"))
=> (for [A list1 B list2] (str A "-" B))
("pink-dog" "pink-cat" "green-dog" "green-cat")

当我尝试单独创建一个向量,并以此作为绑定我打的问题。在这里,我手动创建绑定向量:

When I try to create a vector separately and use this as the binding I hit problems. Here I manually create the bindings vector:

=> (def testvector (vec (list 'A list1 'B list2)))

这似乎罚款:

=> testvector
[A ("pink" "green") B ("dog" "cat")]
=> (class testvector)
clojure.lang.PersistentVector

然而,

=> (for testvector (str A "-" B))
#<CompilerException java.lang.IllegalArgumentException: for requires a vector for its binding (NO_SOURCE_FILE:36)>

我不明白,为什么作为在绑定使用时testvector不被视为一个载体。在抓救命稻草,我把在方括号testvector这使的宏快乐(它看到一个向量),但现在我有一个元素的载体(即在载体中的向量),这不工作,因为绑定需要是对名称和收藏。

I don't understand why testvector isn't considered a vector when used as the binding in for. Grasping at straws, I put testvector in square brackets which keeps the for macro happy (it sees a vector) but now I have a vector with one element (i.e. a vector within a vector) and this doesn't work because the binding needs to be pairs of name and collection.

=> (for [testvector] (str A "-" B))
#<CompilerException java.lang.IllegalArgumentException: for requires an even number of forms in binding vector (NO_SOURCE_FILE:37)>

如何动态传递的载体作为约束性,为将AP preciated任何建议。

Any suggestions on how to dynamically pass a vector as a binding to for would be appreciated.

推荐答案

关键在于的的是一个宏。在宏扩展的时候,testvector是一个符号。它将评估在评估时间的载体,但它不是从的角度向量中的的宏。

The key is that for is a macro. At macro-expansion time, testvector is a symbol. It will evaluate to a vector at evaluation time, but it's not a vector from the perspective of the for macro.

user=> (defmacro tst [v] (vector? v))
#'user/tst
user=> (tst testvector)
false
user=> (vector? testvector)
true
user=> (defmacro tst2 [v] `(vector? ~v))
#'user/tst2
user=> (tst2 testvector)
true

如果您检查的信号源的的宏(在core.clj),你会看到的的使用一个不带引号的矢量?打电话,就像 TST 的在上面的例子。

If you check the source for the for macro (in core.clj), you'll see that for uses an unquoted vector? call, just like tst in the example above.

这篇关于问题传递一个矢量作为绑定到宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆