检查 defmacro (clojure) 中的符号相等性

发布于 2025-01-09 11:00:51 字数 288 浏览 4 评论 0原文

这将返回false

(defmacro scratch [pattern]
  `(= 'b (first ~pattern)))

(scratch '(b))

然而,以下的输出是b

(defmacro scratch2 [pattern]
  `(first ~pattern))

(scratch2 '(b))

如何设置第一个宏返回 true

This returns false.

(defmacro scratch [pattern]
  `(= 'b (first ~pattern)))

(scratch '(b))

However, the output of the following is b.

(defmacro scratch2 [pattern]
  `(first ~pattern))

(scratch2 '(b))

How do I setup the first macro to return true?

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

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

发布评论

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

评论(1

寒尘 2025-01-16 11:00:51

正在发生这种情况,因为您在宏中引入的 'b 是命名空间的:

例如:

user> (defmacro nsmac []
        `(namespace 'b))

user> (nsmac)
;;=> "user"

而您传递的值不是:

user> (namespace (first '(b)))
;;=> nil

所以,您可以将命名空间符号传递给宏,如下所示:

user> (scratch '(user/b)) 
;;=> true

或者您可以修复宏以使用无命名空间符号(qoute-unquote 的已知技巧):

(defmacro scratch [pattern]
  `(= '~'b (first ~pattern)))

user> (scratch '(b)) 
;;=> true

但您真正想要的是在编译时检查这个符号,因为您拥有的这个宏作为普通函数更好,因为它不使用任何与宏相关的优点。

它可能看起来像这样:

(defmacro scratch [pattern]
  (= 'b (first pattern)))

(scratch (b))
;;=> true

可以找到有关命名空间的信息 本文

that is happening, because the 'b that you introduce in macro is namespaced:

example:

user> (defmacro nsmac []
        `(namespace 'b))

user> (nsmac)
;;=> "user"

while the value you pass isn't:

user> (namespace (first '(b)))
;;=> nil

so, you can pass the namespaced symbol to a macro, like this:

user> (scratch '(user/b)) 
;;=> true

or you can fix you macro to use unnamespaced symbol (known trick with qoute-unquote):

(defmacro scratch [pattern]
  `(= '~'b (first ~pattern)))

user> (scratch '(b)) 
;;=> true

but what you really want, is to check this one in compile-time, because this macro you have is better as a plain function, since it doesn't employ any macro-related goodness.

It could look like this:

(defmacro scratch [pattern]
  (= 'b (first pattern)))

(scratch (b))
;;=> true

something about namespacing can be found in this article

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文