F# Medium · Lesson 1 · On the house

Active patterns

Single-case, multi-case, and partial active patterns to name match logic. Lesson 1 is free — on the house.

Lessons · F# Medium · Lesson 1 of 10 · On the house

Active patterns

Single-case, multi-case, and partial active patterns to name match logic.

Illustration for F#
Lesson 1 is on the house.

Active patterns let you define your own match cases. Multi-case: let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd.

Partial patterns may not match and return an option: let (|Int|_|) (s: string) = match System.Int32.TryParse s with | true, n -> Some n | _ -> None.

Parameterized partial patterns take arguments first: let (|Prefix|_|) (p: string) (s: string) = ... used as | Prefix "cmd:" rest -> ....

Single-case patterns transform a value: let (|Lower|) (s: string) = s.ToLower().

They keep match readable when the test is more than a literal or shape.

active patterns

let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd
let (|Int|_|) (s: string) =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | _ -> None
let (|Prefix|_|) (p: string) (s: string) =
    if s.StartsWith p then Some (s.Substring p.Length) else None

let parse input =
    match input with
    | Prefix "add " (Int n) -> sprintf "add %d (%s)" n (match n with Even -> "even" | Odd -> "odd")
    | Prefix "say " text -> sprintf "say '%s'" text
    | Int n -> sprintf "number %d" n
    | _ -> "unknown"

["add 7"; "say hi"; "42"; "add x"; "?"] |> List.iter (parse >> printfn "%s")
Match this when you type.

Quiz

What does a partial active pattern return?

Quiz

Which syntax names a partial active pattern?

Quiz

What does parse "add x" return?

Quiz

What is the benefit of active patterns?

Check

Match the still for: Active patterns.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.