Chapter 6. Pattern Matching
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.
BASICS
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:
The
match
keyword, preceding the expression to be evaluatedThe
with
keyword, indicating the start of one or more various values to compare againstThe 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 ...
Get Professional F# 2.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.