macros - 检查宏内函数的相等性

标签 macros clojure

我有一个宏,我需要检查传递表单的第一个元素是否正是 clojure.core/not 函数。我怎样才能实现这一目标?

(defmacro foo [form]
  (println (= clojure.core/not (first form)))) ; expect true here, but its false

我像这样使用该宏:

(foo (not smthng))

我听说过用 #' 解析符号,但是在这种情况下它对我有什么帮助(如果它甚至可能有帮助的话)? 欢迎任何想法。

最佳答案

在上面的宏中,没有进行符号的语法引用/命名空间,因此形式中的第一件事就是“not”。

(defmacro foo [form]
  (println (first form)))

(foo (not nil))
;=> not

因此,用于检查第一个符号是否的简单宏将是:

(defmacro foo [form]
   (println (= 'not (first form))))

编辑

为了确保您拥有正确的 clojure.core/not(而不是其他可能已引用的内容),您可以使用 resolve 函数来获取完全合格的变量。

(defmacro foo [form]
  (if (= #'clojure.core/not (resolve (first form)))
    (println "(first form) is clojure.core/not")
    (println "(first form) is not clojure.core/not")))

 (foo (not nil))
 ;;=> "(first form) is clojure.core/not"

 (foo (+ 3 4))
 ;;=> "(first form) is not clojure.core/not"

关于macros - 检查宏内函数的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18504781/

相关文章:

Excel 检测并跟踪任何工作表中的(值)变化

c++ - 使用#pragma 和#ifdef 的多行宏

c - Linux内核的__is_constexpr宏

在 Vim 中搜索 "off the record",或者从搜索历史中删除搜索模式?

C++ 连接 __func__ 和 const char 文字

clojure - Clojure Ring/Compojure REPL 中的动态处理程序更新

macros - 在交换中调用带有字符串的 Clojure 函数?

function - 使用或条件在 clojure 中循环

clojure - 如果线程在 `swap!` 期间更改原子的值会发生什么?

postgresql - Clojure - Postgres 找不到合适的驱动程序