何时在 clojure 中使用“constantly”,其参数如何以及何时求值?
在另一个问题的接受答案中,在运行时设置 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当 API 需要一个函数而您只需要一个常量时,
constantly
函数非常有用。问题中提供的示例就是这种情况。大多数
alter-*
函数(包括alter-var-root
)采用一个函数,允许调用者根据其旧值修改某些内容。即使您只希望新值为 7(忽略旧值),您仍然需要提供一个函数(仅提供 7 将导致尝试对其求值,这将失败)。因此,您必须提供一个仅返回 7 的函数。(constantly 7)
仅生成此函数,从而节省了定义它所需的工作。编辑:对于问题的第二部分,
constantly
是一个普通函数,因此它的参数在构造常量函数之前被评估。因此,(constantly @myref)
始终返回调用constantly
时myref
引用的值,即使稍后发生更改。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 (includingalter-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 bymyref
at the timeconstantly
was called, even if it is changed later.