5 ms·
Re: the language feature: This is standard in ML-family/typed functional languages (OCaml, Haskell...), and lately has been being adopted by a lot of newer lang
by zenhack 7y ago
Re: the language feature: This is standard in ML-family/typed functional languages (OCaml, Haskell...), and lately has been being adopted by a lot of newer languages, including Rust and Swift.
- gpm 7y agoI 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...
- hermitdev 7y agoPattern matching has been added in C# 8.0. See: https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching https://docs.microsoft.com/en-us/dotnet/csharp/pattern-match...