Created
July 26, 2024 22:35
-
-
Save asaaki/37c749ef07ebb360dd6631ac677141f4 to your computer and use it in GitHub Desktop.
oceanically moisted fizzbuzz
This file contains 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
type Predicates = std::collections::BTreeMap<Predicate, String>; | |
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] | |
struct Predicate(fn(u64) -> bool); | |
fn main() { | |
let inputs = 0..=100; | |
let mut predicates = Predicates::new(); | |
predicates.insert(Predicate(|v| v % 3 == 0), "Fizz".to_string()); | |
predicates.insert(Predicate(|v| v % 5 == 0), "Buzz".to_string()); | |
evaluate(inputs, predicates).for_each(|v| println!("{v}")); | |
} | |
fn evaluate( | |
inputs: impl Iterator<Item = u64>, | |
predicates: Predicates, | |
) -> impl Iterator<Item = String> { | |
inputs.map(move |v| { | |
predicates | |
.iter() | |
.filter_map(|(p, fv)| (p.0)(v).then_some(fv.to_owned())) | |
.reduce(|a, b| format!("{a}{b}")) | |
.unwrap_or(v.to_string()) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment