Safer Programming with F# – Pattern Matching

F# is a wonderful language. It’s a mixed-paradigm programming language, but it mainly tries to get you to program in a Functional manner. When I was first evaluating it, I was worried that it would be a big warty mess like Scala (no offense!) — but I was pleasantly surprised by F#.

This is a blog post dives into one of the useful features of the language — Pattern Matching[1] — and shows how you can use it to write simpler, safer code.

Pattern Matching is if…else or switch…case on steroids. Here’s a quick example:

You can match on multiple values at once

This sort of approach lets you build up a decision table in a very quick and readable manner.

Pattern matching forces you to be exhaustive

If you miss a possible decision path, the compiler will raise a warning. This forces you take care of every eventuality, unlike switch.
(You do take care to ensure that all compiler warnings are taken care of, don’t you?)

With the proper alignment (as above), this becomes very readable. This technique reminds me of a demo of the Subtext language I had seen a while back: while this isn’t as powerful as what that talk shows, it’s still much better than writing a 3 level nested condition that requires mental gymnastics in order to understand.