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
