Skip to content

Instantly share code, notes, and snippets.

@Rudxain
Forked from rust-play/playground.rs
Last active May 16, 2024 21:45
Show Gist options
  • Save Rudxain/75776f52ac61711419597bf745e82972 to your computer and use it in GitHub Desktop.
Save Rudxain/75776f52ac61711419597bf745e82972 to your computer and use it in GitHub Desktop.
My impl of fizz-buzz in purely type-safe Rust
use num_integer::Integer; // 0.1
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum S {
F,
B,
FB,
}
fn fb<T: Integer>(n: &T) -> Option<S> {
let n3 = T::one() + T::one() + T::one();
let n5 = T::one() + T::one() + T::one() + T::one() + T::one();
let m3 = n.is_multiple_of(&n3);
let m5 = n.is_multiple_of(&n5);
if m3 && m5 {
return Some(S::FB);
}
if m3 {
return Some(S::F);
}
if m5 {
return Some(S::B);
}
None
}
#[must_use]
const fn fbu(n: usize) -> Option<S> {
if n % 15 == 0 {
return Some(S::FB);
}
if n % 3 == 0 {
return Some(S::F);
}
if n % 5 == 0 {
return Some(S::B);
}
None
}
fn main() {
for i in 0..u8::MAX {
match fb(&i) {
Some(s) => println!(
"{}zz",
match s {
S::F => "Fi",
S::B => "Bu",
S::FB => "FizzBu",
}
),
_ => println!("{i}"),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment