gpt4 book ai didi

scala - Scala 的 seq.reduceOption 的 Clojure 等价物是什么?

转载 作者:行者123 更新时间:2023-12-04 15:52:57 24 4
gpt4 key购买 nike

在 Scala 的 Collections 库中 - 我们看到 Seq Class它有 reduceOption 方法:

def reduceOption[A1 >: A](op: (A1, A1) ⇒ A1): Option[A1]

Reduces the elements of this sequence, if any, using the specified associative binary operator."

这有 another great explanation here :

Here comes reduceOption to save the day! If the reduce would fail because the collection was empty, it will just return a None instead, and a Some(returnvalue) for nonempty collections.

我的问题是:Scala 的 seq.reduceOption 在 Clojure 中的等效项是什么?

最佳答案

简称为reduce:

user> (reduce + (range 1e6))
499999500000

user> (reduce + [])
0

在第二种情况下,零的结果来自加法的标识值为零的事实,因此如果您调用不带参数的 + 函数,它将返回 0。对于 * 返回值将是一个。这要求您传递的函数能够处理用零个、一个或两个参数调用的情况。您可以通过将初始值指定为第三个参数来防止此行为,在这种情况下,如果列表为空,则永远不会调用您的缩减函数。

user> (reduce * -1 [])
-1

Reduce 在调用支持此功能的集合(例如向量)时也使用 forkjoin 框架。

关于scala - Scala 的 seq.reduceOption 的 Clojure 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740330/

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