Hi!
I am learning how to write declarative macros, and have a question regarding the following problem:
- Take variable number of comma-separated expressions as input
- Print expressions by pairs, repeating until no pair-wise match is found
- Should also work for odd number of expr by printing the last argument at the end
Here's my naive attempt at solving the problem:
macro_rules! disp {
($($x:expr, $y:expr),*) => {{
$(println!("{}, {}", $x, $y);)*
}};
($($x:expr, $y:expr)*, $z:expr) => {{
$(println!("{}, {}", $x, $y);)*
println!("{}",$z);
// Actual usecase is: pair!($(pair!($x, $y)),* , $z)
}};
}
fn main() {
disp!(1, 2, 3); // This works
// disp!(1, 2, 3, 4, 5); // This doesn't work
}
For even number of inputs the first match arm works fine, but for odd number of inputs, the second match arm doesn't actually work as I intended, i.e. it doesn't match repeatedly if any odd number of inputs greater than 3 is used.
The reason I want to process the inputs by pairs instead of using a single expression is because I am calling another macro that only takes 2 inputs and performs some operation. It's not so easy to modify the said macro, but I want to make it work for more than 2 inputs with methods discussed above.
Any guidance would be appreciated! Thank you.