Alex Rivera | Logout

Explaining pattern matching vs switch

Asked 2008-10-14T03:22:37.200
77

I have been trying to explain the difference between switch statements and pattern matching(F#) to a couple of people but I haven't really been able to explain it well..most of the time they just look at me and say "so why don't you just use if..then..else".

How would you explain it to them?

Edit
Report

1 Answer

5

Pattern matches in OCaml, in addition to being more expressive as mentioned in several ways that have been described above, also give some very important static guarantees. The compiler will prove for you that the case-analysis embodied by your pattern-match statement is:

  • exhaustive (no cases are missed)
  • non-redundant (no cases that can never be hit because they are pre-empted by a previous case)
  • sound (no patterns that are impossible given the datatype in question)

This is a really big deal. It's helpful when you're writing the program for the first time, and enormously useful when your program is evolving. Used properly, match-statements make it easier to change the types in your code reliably, because the type system points you at the broken match statements, which are a decent indicator of where you have code that needs to be fixed.

answered 2009-02-08T14:54:02.017

Your Answer