gpt4 book ai didi

clojure - 何时在 clojure 中使用 `constantly`,如何以及何时评估其参数?

转载 作者:行者123 更新时间:2023-12-03 14:58:00 25 4
gpt4 key购买 nike

在另一个问题的公认答案中,Setting Clojure "constants" at runtime clojure 函数 constantly用来。
constantly的定义看起来像这样:

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

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

在上一个问题中给出的答案中,经常使用如下:
(declare version)

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

因此,constant 返回的函数会直接对其结果进行评估。我很困惑这有什么用。我可能不明白 x将在包含和不包含在 `constantly' 中进行评估。

我应该什么时候使用 constantly为什么有必要?

最佳答案

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

大部分alter-*函数(包括 alter-var-root )接受一个函数,以允许调用者根据其旧值修改某些内容。即使您只希望新值是 7(不考虑旧值),您仍然需要提供一个函数(仅提供 7 将导致尝试评估它,这将失败)。所以你必须提供一个只返回 7 的函数。(constantly 7)只生成这个函数,省去了定义它所需的工作。

编辑:至于问题的第二部分,constantly是一个普通函数,所以它的参数在构造常量函数之前被评估。所以(constantly @myref)始终返回 myref 引用的值当时constantly被调用,即使后来更改。

关于clojure - 何时在 clojure 中使用 `constantly`,如何以及何时评估其参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4016995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com