Skip to content

Instantly share code, notes, and snippets.

@asaaki
Created July 26, 2024 22:35
Show Gist options
  • Save asaaki/37c749ef07ebb360dd6631ac677141f4 to your computer and use it in GitHub Desktop.
Save asaaki/37c749ef07ebb360dd6631ac677141f4 to your computer and use it in GitHub Desktop.
oceanically moisted fizzbuzz
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