Skip to content

Instantly share code, notes, and snippets.

@seanjensengrey
Last active July 28, 2017 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanjensengrey/31c07d1da15ef881472708083fac5dfc to your computer and use it in GitHub Desktop.
Save seanjensengrey/31c07d1da15ef881472708083fac5dfc to your computer and use it in GitHub Desktop.
rust fizz buzz
use std::collections::HashMap;
type BuzzFn<'a> = Box<(Fn(i32) -> String) + 'a>;
fn mbfn<'a, F>(f: F) -> BuzzFn<'a>
where F: Fn(i32) -> String + 'a {
Box::new(f) as BuzzFn
}
fn do_buzz() {
fn test(x:i32) -> (bool,bool) {
(x % 3 == 0, x % 5 == 0)
}
let mut table = HashMap::new();
table.insert((false,false), mbfn(|x:i32| { x.to_string() }));
table.insert((true ,false), mbfn(|x:i32| { "Fizz".to_string() }));
table.insert((false,true), mbfn(|x:i32| { "Buzz".to_string() }));
table.insert((true ,true), mbfn(|x:i32| { "FizzBuzz".to_string() }));
for x in 1..31 {
println!("{:}", table.get(&test(x)).map(|f| f(x)).unwrap());
}
}
fn main() {
do_buzz();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment