I have an input vector which contains numbers. In an output vector, I need to get a sequence of partial products but in right-to-left order. The last element of the output m
This behavior is actually explicitly described in the documentation:
Notes about side effects
The map iterator implements DoubleEndedIterator, meaning that you can also map backwards:
[…]
But if your closure has state, iterating backwards may act in a way you do not expect. […]
A way to solve this would be by adding an intermediary collect to be sure that the second rev
does not apply on the Map
:
fn main() {
let input = vec![2, 3, 4];
let mut prod = 1;
let p: Vec = input
.iter()
.map(|v| {
prod *= v;
prod
}).rev()
.collect::>()
.into_iter()
.rev()
.collect();
println!("{:?}", p);
}
But that requires an extra allocation. Another way would be to collect, and then reverse:
fn main() {
let input = vec![2, 3, 4];
let mut prod = 1;
let mut p: Vec = input
.iter()
.rev()
.map(|v| {
prod *= v;
prod
}).collect();
p.reverse();
println!("{:?}", p);
}