Clojure:确定变量是否已声明
如何测试变量是否已被声明或分配(即,当我期望程序调用类似这样的代码时(def a (create-a)),检查是否定义了“a”?
以及相关的——如何这个问题的答案涉及解析已声明的符号(即函数)的问题 Clojure:确定函数是否存在
似乎定义的变量应该在与定义的函数具有相同的意义,但我发现确定函数是否存在的解决方案不足以确定变量是否存在。
一些上下文:我正在为多开发人员项目编写单元测试,并且想要进行。确定测试数据和不同类中的方法已经定义,由于 clojure 没有良好的 IDE 支持,在我看来,鉴于其松散的结构,最好在测试其输出之前测试方法名称和变量名称的存在。 / 内容。
How can I test wether a variable has been declared or assigned (i.e. check if "a" is defined, when I expect a program to call some code like this (def a (create-a)) ?
And related --- how does the answer to this question relate to the problem of resolving a symbol (i.e. a function) which has been declared ? Clojure: determine if a function exists
It seems like a defined variable should be checkable in the same sense that a defined function is, but I'm finding that the solution for determining if a function exists is not sufficient for determining wether a variable exists.
Some context : I'm writing unit tests for a multideveloper project, and want to make sure that the test data, and the methods in different classes have been defined. Since there is no good IDE support for clojure, it seems to me that, given its loose structure, it is good to test method names and variable names existence before testing their outputs / content.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 resolve 来查看变量是否已绑定/定义:
或者你可以布尔检查它,如果你需要真/假:
You can use resolve to see if the variable was bound/defined:
or you can boolean check it, if you need true/false:
一种方法是使用 ns-resolve ,例如:
请注意,如果您对要检查的符号进行命名空间限定,那么作为第一个参数传递的内容(上例中的
*ns*
)并不重要:<一个@tolitius 提到的 href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/resolve" rel="nofollow">resolve 函数实际上是
ns-resolve
其中名称空间参数始终计算为 ns,具体取决于用例,它可能会更方便。One way to do this is to use ns-resolve, for example:
Note that if you namespace-qualify the symbol to be checked then what you pass as first argument (
*ns*
in the example above) doesn't matter:The resolve function mentioned by @tolitius is actually a shorthand for
ns-resolve
where the namespace argument always evaluates to ns, depending on the use case it might be more handy.正如其他人所说,如果定义了符号,
resolve
将返回符号的 var,否则返回 nil。此外,您可以使用bound?
检查 var 是否有绑定的值。As others have said,
resolve
will return the var for a symbol if there is one defined, or nil. Further, you can check if the var has a value bound to it by usingbound?
.这太疯狂了。您确实希望测试能够说“哎呀!您忘记定义
foobar
!”而不是仅仅尝试运行 foobar 并看到 Clojure 的“无法解析符号”消息?你从中得到什么?您会丢失堆栈跟踪,例如,如果其他代码通过了错误的函数名称,这可能会很有用。知道哪一行拼写错误 foobar 比搜索整个测试命名空间要好得多。
This is nuts. You really want a test to say "Oops! You forgot to define
foobar
!" instead of just trying to runfoobar
and seeing Clojure's "Unable to resolve symbol" message?What do you gain from this? You lose the stacktrace, which could be useful if, for example, the test is passed the wrong function name by some other code. Much better to know what line mis-spelled foobar than to search through your whole test namespace.