3 ms·
I feel like the "canonical" example of using pattern matching for nested if statements is fizzbuzz fn main() { for i in 1..102 { match
by gpm 7y ago
I feel like the "canonical" example of using pattern matching for nested if statements is fizzbuzz
fn main() {
for i in 1..102 {
match (i % 3 == 0, i % 5 == 0) {
(true, true) => println!("FizzBuzz"),
(true, false) => println!("Fizz"),
(false, true) => println!("Buzz"),
(false, false) => println!("{}", i)
}
}
}
Not only is it obviously correct, but if you somehow manage to forget a case the compiler will tell you.
- egwynn 7y agoPeople give me funny looks when I tell them that I wish all languages had exhaustively-checked destructured pattern matching, but I really do think it’s one of the best “advanced” language features around!
- jacobush 7y agoCouldn't you do this with an anonymous function in languages which have those? Which would look like: { if A && B return println("FizzBuss"); if A && !B return println("Fizz"); if !A && B return println("Buzz"); if !A && !B return println("{}", i); }
- Hello71 7y agothat just seems to being us back to the problem of not wanting to re-evaluate the functions...