F# Simple Active Patterns


Example

Active patterns are a special type of pattern matching where you can specify named categories that your data may fall into, and then use those categories in match statements.

To define an active pattern that classifies numbers as positive, negative or zero:

let (|Positive|Negative|Zero|) num = 
    if num > 0 then Positive 
    elif num < 0 then Negative
    else Zero

This can then be used in a pattern matching expression:

let Sign value = 
    match value with
    | Positive -> printf "%d is positive" value
    | Negative -> printf "%d is negative" value
    | Zero -> printf "The value is zero"

Sign -19 // -19 is negative
Sign 2 // 2 is positive
Sign 0 // The value is zero