I encountered this competitive programming problem:
nums
is a vector of integers (length n
)ops
is a vector of strings containing +
and -
(length n-1
)It can be solved with the reduce
operation in Kotlin like this:
val op_iter = ops.iterator();
nums.reduce {a, b ->
when (op_iter.next()) {
"+" -> a+b
"-" -> a-b
else -> throw Exception()
}
}
reduce
is described as:
Accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element.
It looks like Rust vectors do not have a reduce
method. How would you achieve this task?
Edited: since Rust version 1.51.0, this function is called reduce
Be aware of similar function which is called fold. The difference is that reduce
will produce None
if iterator is empty while fold
accepts accumulator and will produce accumulator's value if iterator is empty.
Outdated answer is left to capture the history of this function debating how to name it:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With