Skip to Main Content
Professional F# 2.0
book

Professional F# 2.0

by Ted Neward, Aaron C. Erickson, Talbott Crowell, Richard Minerich
June 2010
Intermediate to advanced content levelIntermediate to advanced
432 pages
10h 44m
English
Wrox
Content preview from Professional F# 2.0

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Book of F#

The Book of F#

Dave Fancher
Beginning F# 4.0

Beginning F# 4.0

Robert Pickering, Kit Eason

Publisher Resources

ISBN: 9780470528013Purchase book