Side effects in fold/reduce?

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.

Generally, a more idiomatic way might be to use windows (or array_windows or tuple_windows) and then for_each (or just a for loop).

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


Ah, yes the tuple_windows method looks like a good one. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.