dtolnay / seq-macro

Macro to repeat sequentially indexed copies of a fragment of code
Apache License 2.0
137 stars 5 forks source link

Allow iterating backwards #20

Open chrisbouchard opened 2 years ago

chrisbouchard commented 2 years ago

It would be very convenient if this library supported backwards iteration of the range. Here's my use case: I have a trait called Undo that represents an action that can be undone. I would like to implement this trait for tuples, to allow a sequence of actions to be undone. The problem is that the tuples ought to be undone in reverse, starting from the end of the tuple.

I'd love to write something like

seq!(N in 2..=4 {
    #(
        seq!(I in 0..N {
            impl<T, #( U~I, )*> Undo for (#( U~I, )*)
            where
                #(U~I: Undo<Target = T>,)*
            {
                type Target = T;

                fn revert(self, target: &mut Self::Target) {
                    seq!(J in (0..N).rev() {
                        self.J.revert(target);
                    });
                }
            }
        });
    )*
});

Or alternately, if there were a way I could handle the reverse indexing myself like

seq!(N in 2..=4 {
    #(
        seq!(I in 0..N {
            impl<T, #( U~I, )*> Undo for (#( U~I, )*)
            where
                #( U~I: Undo<Target = T>, )*
            {
                type Target = T;

                fn revert(self, target: &mut Self::Target) {
                    #( self.#(N - I).revert(target); )*
                })
            }
        });
    )*
});
tarasbogach commented 1 year ago

21 Just made a pull request about it.