Skip to content

Instantly share code, notes, and snippets.

@jnordwick
Created July 30, 2015 22:13
Show Gist options
  • Save jnordwick/1473d5533ca158d47ba4 to your computer and use it in GitHub Desktop.
Save jnordwick/1473d5533ca158d47ba4 to your computer and use it in GitHub Desktop.
count, sum, and avg macros in rust
macro_rules! avg {
($($t:expr),*) => (sum!($($t),*)/count!($($t),*));
}
macro_rules! count {
($h:expr) => (1);
($h:expr, $($t:expr),*) =>
(1 + count!($($t),*));
}
macro_rules! sum {
($h:expr) => ($h);
($h:expr, $($t:expr),*) =>
($h + sum!($($t),*));
}
fn main() {
let i = avg![1,2,4,6,8,5,3,4,7,4,5,7];
println!("{}", i);
}
@NickLarsenNZ
Copy link

NickLarsenNZ commented Jan 23, 2021

I was trying to do the same sort of thing as an exercise. The only difference is that I called the macro on both sides of the operation (because I had debug println! calls).

macro_rules! sum {
    ($h:expr) => ($h);              // so that this would be called, I ...
    ($h:expr, $($t:expr),*) =>
        (sum!($h) + sum!($($t),*)); // ...call sum! on both sides of the operation
}

same with the count! macro:

macro_rules! count {
    ($h:expr) => (1);
    ($h:expr, $($t:expr),*) =>
        (count!(1) + count!($($t),*));
}

Edit: Oh, and I was using + instead of *.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment