From 4a09d053ac366d07692994fd657b41e6439dc0ae Mon Sep 17 00:00:00 2001 From: Martin Geisler Date: Wed, 3 May 2023 09:56:58 +0200 Subject: [PATCH] Simplify fizz buzz slide (#595) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit There is no need to introduce `match` here where we don’t have time to talk about it in detail. --- src/basic-syntax/functions.md | 41 ++++++++++++----------------------- 1 file changed, 14 insertions(+), 27 deletions(-) diff --git a/src/basic-syntax/functions.md b/src/basic-syntax/functions.md index 705911ea..3858f5e9 100644 --- a/src/basic-syntax/functions.md +++ b/src/basic-syntax/functions.md @@ -4,28 +4,28 @@ A Rust version of the famous [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) ```rust,editable fn main() { - fizzbuzz_to(20); // Defined below, no forward declaration needed + print_fizzbuzz_to(20); } -fn is_divisible_by(lhs: u32, rhs: u32) -> bool { - if rhs == 0 { - return false; // Corner case, early return +fn is_divisible(n: u32, divisor: u32) -> bool { + if divisor == 0 { + return false; } - lhs % rhs == 0 // The last expression in a block is the return value + n % divisor == 0 } -fn fizzbuzz(n: u32) -> () { // No return value means returning the unit type `()` - match (is_divisible_by(n, 3), is_divisible_by(n, 5)) { - (true, true) => println!("fizzbuzz"), - (true, false) => println!("fizz"), - (false, true) => println!("buzz"), - (false, false) => println!("{n}"), +fn fizzbuzz(n: u32) -> String { + let fizz = if is_divisible(n, 3) { "fizz" } else { "" }; + let buzz = if is_divisible(n, 5) { "buzz" } else { "" }; + if fizz.is_empty() && buzz.is_empty() { + return format!("{n}"); } + format!("{fizz}{buzz}") } -fn fizzbuzz_to(n: u32) { // `-> ()` is normally omitted +fn print_fizzbuzz_to(n: u32) { for i in 1..=n { - fizzbuzz(i); + println!("{}", fizzbuzz(i)); } } ``` @@ -36,19 +36,6 @@ fn fizzbuzz_to(n: u32) { // `-> ()` is normally omitted * Declaration parameters are followed by a type (the reverse of some programming languages), then a return type. * The last expression in a function body (or any block) becomes the return value. Simply omit the `;` at the end of the expression. * Some functions have no return value, and return the 'unit type', `()`. The compiler will infer this if the `-> ()` return type is omitted. -* The range expression in the `for` loop in `fizzbuzz_to()` contains `=n`, which causes it to include the upper bound. -* The `match` expression in `fizzbuzz()` is doing a lot of work. It is expanded below to show what is happening. - - (Type annotations added for clarity, but they can be elided.) - - ```rust,ignore - let by_3: bool = is_divisible_by(n, 3); - let by_5: bool = is_divisible_by(n, 5); - let by_35: (bool, bool) = (by_3, by_5); - match by_35 { - // ... - ``` - - +* The range expression in the `for` loop in `print_fizzbuzz_to()` contains `=n`, which causes it to include the upper bound.