Pattern Matching

Powerful control flow in F#

Basic Pattern Matching

let describeNumber x =
    match x with
    | 0 -> "Zero"
    | 1 -> "One"
    | n when n < 0 -> "Negative"
    | _ -> "Positive number"

Advanced Patterns

type Shape =
    | Circle of radius:float
    | Rectangle of width:float * height:float

let area shape =
    match shape with
    | Circle r -> Math.PI * r * r
    | Rectangle (w, h) -> w * h

Active Patterns

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

let testNumber n =
    match n with
    | Even -> printfn "%d is even" n
    | Odd -> printfn "%d is odd" n