Chuyển đến nội dung

Bài 27 · Pattern Matching and Options

Active Patterns

Learn F# active patterns: single-case, multi-case and partial patterns with the banana-clip syntax, parameterized patterns, parsing with patterns, and how they make match expressions read like the domain.

Ordinary patterns match the structure a type exposes: union cases, tuples, list cells. But often the question you want to ask is not about structure. Is this string a number? Is this integer even? Does this text look like an email address? Active patterns let you define your own named patterns that run a function behind the scenes and then take part in match like any other pattern.

Single-case active patterns

The simplest kind converts a value into another form, always succeeding. The name sits inside "banana clips" (| |):

FSHARP
let (|Celsius|) fahrenheit = (fahrenheit - 32.0) * 5.0 / 9.0

let describe (Celsius c) =
    if c > 30.0 then "hot" elif c < 10.0 then "cold" else "mild"

describe 100.0   // "hot"
describe 50.0    // "mild"

The parameter pattern (Celsius c) calls the function and binds its result to c. This is good for normalising input before matching.

Multi-case active patterns

A multi-case pattern partitions values into up to seven named categories. The function returns one of the cases:

FSHARP
let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd

let parity n =
    match n with
    | Even -> "even"
    | Odd -> "odd"

The compiler treats Even and Odd as a complete set, so a match with both is exhaustive, with no wildcard needed. Cases can carry data:

FSHARP
let (|Positive|Zero|Negative|) (n: int) =
    if n > 0 then Positive n
    elif n = 0 then Zero
    else Negative (abs n)
C# C# stand-in: categorising with a switch and a helper

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Partial active patterns

Most real uses are partial: the pattern may fail to match. Its name ends with |_| and it returns an option:

FSHARP
let (|Integer|_|) (s: string) =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | _ -> None

let (|Float|_|) (s: string) =
    match System.Double.TryParse(s, System.Globalization.NumberStyles.Float,
                                 System.Globalization.CultureInfo.InvariantCulture) with
    | true, f -> Some f
    | _ -> None

let classify input =
    match input with
    | Integer n -> $"int {n}"
    | Float f -> $"float {f}"
    | "" -> "empty"
    | s -> $"text '{s}'"

classify "42"     // "int 42"
classify "3.5"    // "float 3.5"
classify "hello"  // "text 'hello'"

Patterns are tried in order, so Integer runs before Float. A partial pattern behaves like any case inside match, so you can combine it with guards and nest it. For performance you can mark a partial active pattern [<return: Struct>] and return ValueSome / ValueNone to avoid allocating an option (ValueOption).

Parameterized patterns

Active patterns can take extra arguments before the matched value:

FSHARP
open System.Text.RegularExpressions

let (|Regex|_|) pattern input =
    let m = Regex.Match(input, pattern)
    if m.Success then Some [ for g in m.Groups -> g.Value ] else None

let parseCommand line =
    match line with
    | Regex @"^add (\d+) (\d+)$" [ _; a; b ] -> Some (int a + int b)
    | Regex @"^neg (\d+)$" [ _; a ] -> Some (-(int a))
    | _ -> None

parseCommand "add 3 4"   // Some 7
parseCommand "neg 9"     // Some -9
parseCommand "oops"      // None

The pattern Regex @"..." [ _; a; b ] passes the regex as an argument, and the list pattern on the result picks out the captured groups. This one idiom turns a tangled pile of if/else into readable cases. (Here the name Regex shadows the .NET class inside the pattern only; many authors call it Match or Rx to avoid confusion.)

C# C# stand-in: the same command parser with regex and switch

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When to use them

flowchart TD
    A["Need to branch on a value"] --> B{"Is the structure<br/>enough?"}
    B -->|yes| C["Ordinary pattern"]
    B -->|"no, need a test or conversion"| D{"Always succeeds?"}
    D -->|yes, one result| E["Single-case (|Name|)"]
    D -->|yes, several categories| F["Multi-case (|A|B|)"]
    D -->|"may fail"| G["Partial (|Name|_|)"]

Pick the narrowest kind: partial for "maybe", multi-case for "which of these", single-case for "convert first".

Good uses: parsing text, classifying numbers, recognising shapes in expression trees (for example, "a sum with zero"), and wrapping .NET APIs that return null or codes. Poor uses: heavy work repeated in many matches (each active pattern call runs again for every case that mentions it), and cases where a plain union or if is clearer. Active patterns hide a function call, so keep them cheap and well named.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What do the banana clips in (|Even|Odd|) indicate?

    (| ... |) defines an active pattern; the names inside become usable as patterns.
  2. 2. How is a partial active pattern recognisable?

    Partial patterns are written (|Name|_|) and return Some on a match, None otherwise.
  3. 3. How many cases may a multi-case active pattern have at most?

    F# limits multi-case active patterns to seven cases.
  4. 4. What is a downside of active patterns?

    The function is invoked when the pattern is tested, so keep it cheap.

Summary

  • Active patterns turn your own functions into named patterns, written in banana clips.
  • Single-case converts, multi-case classifies into up to seven cases, partial (|_|) may fail.
  • Parameterized patterns accept extra arguments, as with a regex pattern.
  • They make parsing and classification code read like the domain; keep them cheap.

Next: Async Workflows

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.