WHAT'S IN THIS CHAPTER?
Understanding patterns and pattern-matching
Using pattern matching types
Applying pattern guards
Using active patterns
More so than any other construct thus far explored, pattern matching is what distinguishes F# from the other languages in the .NET family. Pattern-matching is a hallmark of the functional language, and its power is something that is rapidly finding its way (in various guises) into other languages.
Fundamentally, pattern-matching looks, on the surface, like a variation on the switch/case construct from the C-family of languages: A value is tested, and depending on its contents, one of several different "branches" of code is evaluated:
let x = 12 match x with | 12 -> System.Console.WriteLine("It's 12") | _ -> System.Console.WriteLine("It's not 12")
The syntax is somewhat similar to the switch/case of C#; broken down, a pattern-match consists of the following:
match keyword, preceding the expression to be evaluated
with keyword, indicating the start of one or more various values to compare against
The vertical pipe character (|) at the start of each match clause to evaluate against
A match clause, which can take one of several different forms as described later in this chapter
The arrow (->), separating the match clause from the expression to execute if the match clause succeeds
As is consistent with F#'s syntax, the underscore (_) character acts as a wildcard when used: anything that doesn't match against preceding ...