何时在 clojure 中使用“constantly”,其参数如何以及何时求值?

发布于 2024-09-28 22:59:22 字数 712 浏览 0 评论 0原文

在另一个问题的接受答案中,在运行时设置 Clojure“常量” clojure 函数使用不断

constantly 的定义如下所示:

(defn constantly
  "Returns a function that takes any number of arguments and returns x."
  {:added "1.0"}
  [x] (fn [& args] x))

文档字符串说明了它的作用,但没有说明为什么要使用它。

在上一个问题给出的答案中,constant 的用法如下:

(declare version)

(defn -main
  [& args]
 (alter-var-root #'version (constantly (-> ...)))
 (do-stuff))

因此,constant 返回的函数直接计算其结果。我很困惑这有什么用。我可能不明白 x 如何在包含和不包含“constantly”的情况下进行评估。

我什么时候应该经常使用以及为什么有必要?

In the accepted answer to another question, Setting Clojure "constants" at runtime the clojure function constantly is used.

The definition of constantly looks like so:

(defn constantly
  "Returns a function that takes any number of arguments and returns x."
  {:added "1.0"}
  [x] (fn [& args] x))

The doc string says what it does but not why one would use it.

In the answer given in the previous question constantly is used as follows:

(declare version)

(defn -main
  [& args]
 (alter-var-root #'version (constantly (-> ...)))
 (do-stuff))

So the function returned by constantly is directly evaluated for its result. I am confused as to how this is useful. I am probably not understanding how x would be evaluated with and without being wrapped in `constantly'.

When should I use constantly and why is it necessary?

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

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

发布评论

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

评论(1

池予 2024-10-05 22:59:22

当 API 需要一个函数而您只需要一个常量时,constantly 函数非常有用。问题中提供的示例就是这种情况。

大多数 alter-* 函数(包括 alter-var-root)采用一个函数,允许调用者根据其旧值修改某些内容。即使您只希望新值为 7(忽略旧值),您仍然需要提供一个函数(仅提供 7 将导致尝试对其求值,这将失败)。因此,您必须提供一个仅返回 7 的函数。(constantly 7) 仅生成此函数,从而节省了定义它所需的工作。

编辑:对于问题的第二部分,constantly 是一个普通函数,因此它的参数在构造常量函数之前被评估。因此,(constantly @myref) 始终返回调用 constantlymyref 引用的值,即使稍后发生更改。

The constantly function is useful when an API expects a function and you just want a constant. This is the case in the example provided in the question.

Most of the alter-* functions (including alter-var-root) take a function, to allow the caller to modify something based on its old value. Even if you just want the new value to be 7 (disregarding the old value), you still need to provide a function (providing just 7 will result in an attempt to evaluate it, which will fail). So you have to provide a function that just returns 7. (constantly 7) produces just this function, sparing the effort required to define it.

Edit: As to second part of the question, constantly is an ordinary function, so its argument is evaluated before the constant function is constructed. So (constantly @myref) always returns the value referenced by myref at the time constantly was called, even if it is changed later.

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