collections - Rust 中 Kotlin 的 `reduce` 操作的替代方案是什么?

标签 collections functional-programming rust reduce

我遇到了这个竞争性编程问题:

  1. nums 是一个整数向量(长度n)
  2. ops 是包含+- 的字符串向量(长度n-1)

可以用reduce来解决在 Kotlin 中的操作是这样的:

val op_iter = ops.iterator();
nums.reduce {a, b ->
    when (op_iter.next()) {
        "+" -> a+b
        "-" -> a-b
        else -> throw Exception()
    }
}

reduce 被描述为:

Accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element.

看起来 Rust 向量没有 reduce 方法。你将如何完成这项任务?

最佳答案

已编辑:自 Rust 版本 1.51.0 起,此函数称为 reduce 请注意名为 fold 的类似功能.不同之处在于,如果迭代器为空,reduce 将生成 None,而 fold 接受累加器,如果迭代器为空,将生成累加器的值。

留下过时的答案来捕捉这个函数争论如何命名的历史:

There is no reduce in Rust 1.48. In many cases you can simulate it with fold but be aware that the semantics of the these functions are different. If the iterator is empty, fold will return the initial value whereas reduce returns None. If you want to perform multiplication operation on all elements, for example, getting result 1 for empty set is not too logical.

Rust does have a fold_first function which is equivalent to Kotlin's reduce, but it is not stable yet. The main discussion is about naming it. It is a safe bet to use it if you are ok with nightly Rust because there is little chance the function will be removed. In the worst case, the name will be changed. If you need stable Rust, then use fold if you are Ok with an illogical result for empty sets. If not, then you'll have to implement it, or find a crate such as reduce.

关于collections - Rust 中 Kotlin 的 `reduce` 操作的替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54897870/

相关文章:

java - 在发生碰撞时从 LinkedHashMap 检索元素的时间复杂度是多少?

java - 如何实现实现 Collections 的模板化类

c# - Linq to NHibernate 返回名称以字符串列表内容开头的实体

functional-programming - 如何将字符串转换为整数数组,包含相应字符的 ascii 值?

haskell - 我使用 randomRIO 错了吗?

rust - 当变量永远不会重新分配时,为什么我需要使用 mut?

java - 我可以获得对 List<> 对象的引用(该对象引用其元素之一)吗?

arrays - Scala - 将 Array[String] 转换为 Array[Double]

hashmap - 模式匹配选项时,引用类型不兼容的匹配臂引发错误

rust - 带有引用的通用参数用作函数指针参数