F# Resources

You are here: main » lang » active_patterns


|

Meta

Active patterns

Active patterns are the way in F# to expand pattern matching (user functions can be called during pattern matching).

Single Case Active Patterns

let (|Rect|) (x:complex) = (x.RealPart, x.ImaginaryPart)
let (|Polar|) (x:complex) = (x.Magnitude, x.Phase)

let add (Rect(ar,ai)) (Rect(br,bi)) = mkRect(ar+br,ai+bi)

Multi-Case Active Patterns

let (|Cons|Nil|) l =
  if List.nonempty l then Cons(List.hd l, List.tl l)
  else Nil

let rec pairSum xs =
  match xs with
   | Cons(x, Cons(y,_)) -> x + y
   | Cons(x, Nil) -> x
   | Nil -> 0

Partial Active Patterns

let (|Positive|_|) n =
  if n >= 0 then Some()
  else None

let (|Int|_|) (o: obj) =
  match o with
  | :? int -> Some(unbox<int> o)
  | _ -> None

match box 4 with
  | Int 0 -> 0
  | Int Positive -> 1
  | _ -> 0

Parameterized Active Patterns

let (|DivisibleBy|_|) x n = if n % x = 0 then Some() else None

match 25 with
  | DivisibleBy 4 () -> false
  | DivisibleBy 5 () -> true
  | _ -> false

let (|ParseRegex|_|) re s =
  let m = Regex(re).Match(s)
  if m.Success
  then Some (List.tl [ for x in m.Groups -> x.Value ])
  else None

match "Peace and love" with
  | ParseRegex "([^ ]*) and ([^ ]*)" [x;y] -> printfn "%s and %s" x y
  | _ -> printfn "Failed"

See also