typestar

Active patterns in F#

Name a classification once; match on it like a built-in.

// An active pattern names a classification and matches on it.
let (|Light|Fair|Heavy|) weightKg =
    if weightKg < 22.0 then Light
    elif weightKg < 30.0 then Fair
    else Heavy

let plan hive weightKg =
    match weightKg with
    | Light -> sprintf "%s: feed heavily before frost" hive
    | Fair -> sprintf "%s: one more syrup round" hive
    | Heavy -> sprintf "%s: ready for winter" hive

plan "Willow" 34.2 |> printfn "%s"
plan "Bramble" 19.5 |> printfn "%s"
plan "Clover" 26.0 |> printfn "%s"

How it works

  1. (|Light|Fair|Heavy|) defines three named outcomes.
  2. The classifier runs when the match consults it.
  3. Callers read as policy: Light feeds, Heavy winters.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
476
Tokens
102
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 94 seconds.

Type this snippet

Step 3 of 3 in Pattern matching, step 9 of 27 in Language basics.

← Previous Next →