liveBook · Manning

Active pattern

As explained in F# in Action: A Revised Edition of Get Programming with F#

An active pattern is an F# pattern definition that encapsulates reusable computation for determining how a value matches.

An active pattern is an F# pattern definition that packages reusable matching logic. It helps replace complicated guards or repeated conditions with readable pattern cases. section 8.1.6 section 16.4.2

Use active patterns when a match is difficult to read, when the same classification appears in several expressions, or when you want to avoid wrapping values in discriminated unions. The pattern function defines cases such as Punctual, MostlyPunctual, or AlwaysLate, and matching applies the appropriate case transparently. section 16.4.2

Classifying a pupil

A verbose grading match can inspect lateness, disciplinaries, and exam results with several guards. An active-pattern version matches those dimensions directly: Punctual, WellBehaved, and TopScore produce an A; less favorable combinations produce B, C, or D. section 16.4.2

let (|Punctual|OccasionallyLate|AlwaysLate|) (v:int) =    #1
    if v = 0 then Punctual                                #2
    elif v < 5 then MostlyPunctual                        #2
    else AlwaysLate                                       #2

This compact definition classifies an integer into named matching cases, which can then be used directly in pattern matches. section 16.4.2

Active patterns are optional rather than everyday requirements. Start with ordinary patterns and guards, then consider an active pattern when duplicated logic or explanatory comments make the match unwieldy. Guards remain useful, but they can reduce exhaustiveness checking and often require a wildcard fallback. section 8.1.6 section 16.4.2

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Defines case-based pattern functions and parameterized matching, but treats advanced details as an initial introduction.
Examples
Classifies pupil performance by exam scores, lateness, and disciplinaries, and contrasts guarded grading with named active-pattern cases.
What it assumes
Assumes familiarity with F# pattern matching and guards while avoiding a requirement to define discriminated-union types.
What you can do after
Apply it via F# pattern matching to simplify repeated or difficult classification logic.
How it connects
Connects active patterns to pattern matching, when guards, wildcards, and discriminated unions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.