Created
July 30, 2015 22:13
-
-
Save jnordwick/1473d5533ca158d47ba4 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
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).same with the
count!
macro:Edit: Oh, and I was using
+
instead of*
.