Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
FizzBuzz in Rust macro
fn main() {
macro_rules! fizzbuzz {
(($($from:tt)*), ($($to:tt)*)) => {
fizzbuzz_rec!(($(($from, $to))*), ());
};
}
macro_rules! fizzbuzz_rec {
(((0, 0) $(($from:tt, $to:tt))*), ($($prefix:tt)*)) => {
fizzbuzz_rec!(($(($from, $to))*), ($($prefix)* 0));
};
(((0, 1) $(($from:tt, $to:tt))*), ($($prefix:tt)*)) => {
fizzbuzz_rec!(($(($from, 1))*), ($($prefix)* 0));
fizzbuzz_rec!(($((0, $to))*), ($($prefix)* 1));
};
(((1, 0) $(($from:tt, $to:tt))*), ($($prefix:tt)*)) => {
};
(((1, 1) $(($from:tt, $to:tt))*), ($($prefix:tt)*)) => {
fizzbuzz_rec!(($(($from, $to))*), ($($prefix)* 1));
};
(($(($from:tt, $to:tt))*), ($($prefix:tt)*)) => {
fizzbuzz_cond!(($($prefix)*), (), (), 0);
};
}
macro_rules! fizzbuzz_cond {
(($($remain:tt)*), (1 1 1 $($mod3:tt)*), ($($mod5:tt)*), $num:expr) => {
fizzbuzz_cond!(
($($remain)*),
($($mod3)*),
($($mod5)*),
$num);
};
(($($remain:tt)*), ($($mod3:tt)*), (1 1 1 1 1 $($mod5:tt)*), $num:expr) => {
fizzbuzz_cond!(
($($remain)*),
($($mod3)*),
($($mod5)*),
$num);
};
((0 $($remain:tt)*), ($($mod3:tt)*), ($($mod5:tt)*), $num:expr) => {
fizzbuzz_cond!(
($($remain)*),
($($mod3)* $($mod3)*),
($($mod5)* $($mod5)*),
2 * $num);
};
((1 $($remain:tt)*), ($($mod3:tt)*), ($($mod5:tt)*), $num:expr) => {
fizzbuzz_cond!(
($($remain)*),
(1 $($mod3)* $($mod3)*),
(1 $($mod5)* $($mod5)*),
1 + 2 * $num);
};
((), (), (), $num:expr) => {
println!("FizzBuzz");
};
((), (), ($($mod5:tt)*), $num:expr) => {
println!("Fizz");
};
((), ($($mod3:tt)*), (), $num:expr) => {
println!("Buzz");
};
((), ($($mod3:tt)*), ($($mod5:tt)*), $num:expr) => {
println!("{}", $num);
};
}
// 1 to 100
// fizzbuzz!((0 0 0 0 0 0 1), (1 1 0 0 1 0 0));
// 1 to 200
fizzbuzz!((0 0 0 0 0 0 0 1), (1 1 0 0 1 0 0 0));
// 1 to 500
// fizzbuzz!((0 0 0 0 0 0 0 0 1), (1 1 1 1 1 0 1 0 0));
// 1 to 1000
// fizzbuzz!((0 0 0 0 0 0 0 0 0 1), (1 1 1 1 1 0 1 0 0 0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment