Pattern Matching!

Pattern matching is great for when you have lots of things that you want to act on based on their properties. At first glance, all that pattern matching does is reduce the amount of typing needed for if statements. And in some cases (such as this one) it doesn't even cut down on the typing! Here is how you would write the same function as before, but using pattern matching:

def sortItems(recyclable):
    """sort the items based on material"""
    case (recyclable):
      match recyclable is aluminum:
        """execute code to put recyclable into the aluminum bin"""
      match recyclable is paper:
          """execute code to put recyclable into the paper bin"""
      match recyclable is plastic:
          """execute code to put recyclable into the plastic bin"""
        raise TypeError("item not recyclable")

As you can see above, we feed the parameter "recyclable" into what is known as a case-match statement. Each "match" line assesses how to handle "recyclable" based on its properties. In this example, pattern matching wasn't very effective, and had the same effect as just using if statements. But stay tuned to see some cases where pattern matching is really powerful!