-
-
Save leobm/c2a30d17e193abede2992b9623135ee1 to your computer and use it in GitHub Desktop.
count, sum, and avg macros in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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