Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an alternative to Kotlin's `reduce` operation in Rust?

I encountered this competitive programming problem:

  1. nums is a vector of integers (length n)
  2. 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?

like image 878
saga Avatar asked Dec 10 '22 03:12

saga


1 Answers

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 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.

like image 114
Vadym Chekan Avatar answered Mar 16 '23 09:03

Vadym Chekan