Usually I think of map, fold/reduce, and friends as pure functions, with no side effects. I was wondering what the rust community thought of using reduce, solely for side effects. Say I have a list of points, and I want to draw a line between each point. The first thing I came up with was something like:
fn draw_line_stub(p1:&(i32,i32), p2:&(i32,i32)) -> () { println!("from {:?} to {:?}",p1,p2); }
fn main() {
let points = [(0,0), (100,0), (100,100), (0,100), (0,0)];
points.iter().reduce(|a, b| { draw_line_stub(a,b); b } );
}
...seems nice and succinct, but again we're only using it to sequence side effects, and throwing away the value, which may violate the spirit of reduce. Thoughts? Is there a more appropriate method to use instead? Seems like a good name might be "between_each" or similar.
That said, nothing's wrong with using reduce/fold for side effects; try_fold is the canonical/root internal iteration implementation, and they all take FnMut specifically to allow for environment-mutating closures.
(Another interesting idea would be for _ in (iter.next(), iter.peek()), as that handles ownership ideally for a consuming iterator of itemwise pairs, but I don't think anyone provides an adaptor for that yet.)