Created
October 26, 2017 20:33
-
-
Save gabrfarina/d2af2d3e9087a870c9df32c32b4380f0 to your computer and use it in GitHub Desktop.
FizzBuzzGenerator
This file contains hidden or 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
#![feature(inclusive_range_syntax, generators, generator_trait, never_type)] | |
use std::ops::{Generator, GeneratorState}; | |
fn is_div_by(n: u64, modulus: u64) -> bool { | |
if n % modulus == 0 { | |
true | |
} else { | |
false | |
} | |
} | |
struct FizzBuzzGenerator { | |
number: u64 | |
} | |
impl FizzBuzzGenerator { | |
fn new() -> FizzBuzzGenerator { | |
FizzBuzzGenerator{number: 0} | |
} | |
} | |
impl Generator for FizzBuzzGenerator { | |
type Yield = String; | |
type Return = !; | |
fn resume(&mut self) -> GeneratorState<Self::Yield, Self::Return> { | |
let is_div_by_3 = is_div_by(self.number, 3); | |
let is_div_by_5 = is_div_by(self.number, 5); | |
let answer: String = match (is_div_by_3, is_div_by_5) { | |
(true, false) => "Fizz".to_string(), | |
(false, true) => "Buzz".to_string(), | |
(true, true) => "FizzBuzz".to_string(), | |
_ => format!("{}", self.number), | |
}; | |
self.number += 1; | |
GeneratorState::Yielded(answer) | |
} | |
} | |
fn main() { | |
let mut fizz_buzz_generator = FizzBuzzGenerator::new(); | |
loop { | |
match fizz_buzz_generator.resume() { | |
GeneratorState::Yielded(answer) => println!("{}", answer), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment