Skip to content

Instantly share code, notes, and snippets.

@de-sh
Last active June 13, 2020 07:01
Show Gist options
  • Save de-sh/a61f4fe902ea158b7495eb5076274dd4 to your computer and use it in GitHub Desktop.
Save de-sh/a61f4fe902ea158b7495eb5076274dd4 to your computer and use it in GitHub Desktop.
Rewriting if-else conditionals as match statements

It is common in computing, to come across a conditional statement that contains a lot of ANDs, ORs and more. With rust-lang's powerful match statement, a programmer can easily convey the message, let's see how.

match statements takes pattern matching to another level. Using the simple syntax, one can also achieve what nested/ladder if-else blocks could. Here is a sample if-else code block.

if year%4 == 0 {
  if year%100 != 0 || year%400 == 0 { 
    println!("Leap Year"); 
  } else { 
    println!("Not a Leap Year"); 
  } 
} else { 
  println!("Not a Leap Year"); 
}

Run in playground

The above program can be rewritten with match where patterns of boolean valued triples that are descriptive of conditions where the algorithm should print "Leap Year".

match (year%4 == 0, year%100 == 0, year%400 == 0) {
    (_, _, true) => println!("Leap Year"),
    (true, false, _) => println!("Leap Year"),
    _ => println!("Not a Leap Year"),
}

Run in playground

You can rewrite the above program by combining the patterns that are indicative of the conditions being right for printing "Leap Year", thus decreasing the number of lines in the program.

match (year%4 == 0, year%100 == 0, year%400 == 0) {
    (_, _, true) | (true, false, _) => println!("Leap Year"),
    _ => println!("Not a Leap Year"),
}

Run in playground

So, that's a pretty simple intro to how match works in rust, but there's a lot more to it than this, we'll discuss that later!

@asdofindia
Copy link

Here's a shorter one:

match (year % 400, year % 100, year % 4) { 
        (0, _, _) | (_, 1 ..= 99, 0)  => println!("Leap Year"),
        _ => println!("Not a Leap Year")
    }

@de-sh
Copy link
Author

de-sh commented Jun 13, 2020

Yes, that would be the next increment from the current state of code, moving from a boolean based conditional to an entirely pattern based match statement. Thanks for the contribution @asdofindia 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment