我遇到了这个竞争性编程问题:
nums
是一个整数向量(长度n
)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 withfold
but be aware that the semantics of the these functions are different. If the iterator is empty,fold
will return the initial value whereasreduce
returnsNone
. If you want to perform multiplication operation on all elements, for example, getting result1
for empty set is not too logical.
Rust does have a
fold_first
function which is equivalent to Kotlin'sreduce
, 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 usefold
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/