O'Reilly logo

Professional F# 2.0 by Richard Minerich, Talbott Crowell, Aaron C. Erickson, Ted Neward

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 evaluated

  • The 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required