gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:34:23 31 4
gpt4 key购买 nike

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

  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/

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