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.


> let isOdd x = (x % 2 = 1)
let describeNumber x =
match isOdd x with
| true -> printfn “number is odd”
| false -> printfn “ number is even”;;

> describeNumber 4;;
number is even
val it : unit = ()


Truth Table
Letz take AND truth table example using type inference on pattern matches. Herez the code:


> let testAND x y =
match x, y with
| true, true -> true
| true, false -> false
| false, true -> false
| false, false -> true
> testAND true false;;
val it: bool = true


Match Failure
If 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.


> let testAND x y =
match x, y with
| true, true -> true
// Commented | true, false -> false
| false, true -> false
| false, false -> true
> testAND true false;;

Microsoft.Fsharp.Core.MatchFailureExcption: The match cases were incomplete at:....
Stopped due to error


Pattern matching rules are checked in the order they are declared.

No comments:

Post a Comment