Sunday, December 18, 2011

F# Pattern Matching

Pattern matching is logically similar to a switch statement in C#, Java, C++, etc; but itz much more powerful. A pattern match is a series of rules that will execute if the pattern matches the input. The pattern match expression then returns the result of the rule that was matched. So, all rules in a pattern match must return the same type.

In F#, you use match and with keywords with a series of pattern rules, followed by an arrow -> for pattern matching. Herez a sample F# pattern match code for Odd validation.

Match FailureIf no match is found during a pattern matching, an exception of type Microsoft.Fsharp.Core.MatchFailureException is raised. You can avoid this by making sure that all possible cases are coverd. Fortunately, F# compiler will issue a warning when it can determine that pattern match rules are incomplete.