Skip to content

Instantly share code, notes, and snippets.

@leobm
Forked from jnordwick/avg.rs
Created December 17, 2024 13:39
Show Gist options
  • Save leobm/c2a30d17e193abede2992b9623135ee1 to your computer and use it in GitHub Desktop.
Save leobm/c2a30d17e193abede2992b9623135ee1 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment