偶尔查看其他人的 Clojure 代码时,我会看到一个通过 defn
定义的函数然后使用 var-quote 语法调用,例如:
user> (defn a [] 1)
#'user/a
user> (a) ; This is how you normally call a function
1
user> (#'a) ; This uses the var-quote syntax and produces the same result
1
对于我的生活,我无法弄清楚这两种调用函数的方式之间的区别。我在 evaluation 中找不到任何内容文档说明当调用的运算符(operator)是 var 时会发生什么,这可能表明为什么首选第二种形式。他们似乎都对
binding
做出了相同的回应。赋值和语法引用。那么,有人可以提供一个代码示例来说明
(a)
之间的区别吗?和 (#'a)
多于?编辑:我知道 var-quote 可用于获取被
let
遮蔽的 var。词法绑定(bind),但在我正在查看的代码中似乎并非如此。
最佳答案
(#'a)
总是指 var a
, 而 (a)
可以被本地绑定(bind)遮蔽:
user> (defn a [] 1)
#'user/a
user> (let [a (fn [] "booh")] [(a) (#'a)])
["booh" 1]
但是 var-quote/function call 的大多数实际用途并不是直接调用 var-quote 表达式,而是缓存它的值,以便高阶构造在传入时引用 var a 的当前值而不是它的值:
(defn a [] 1)
(defn my-call [f] (fn [] (+ 1 (f))))
(def one (my-call a))
(def two (my-call #'a))
(defn a [] 2)
user> (one)
2
user> (two)
3
这对于交互式开发非常有用,在这种开发中,您正在更改一些包装在其他包中的一堆其他功能中的功能。
关于clojure - 使用 var-quote 语法调用 Clojure 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14763301/