Hacker News new | ask | show | jobs
by gpm 2339 days 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.
2 comments

People 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!
Couldn'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);
    }
that just seems to being us back to the problem of not wanting to re-evaluate the functions...