Active Patterns in F#

Active patterns have been causing me a few headaches, trying to understand the syntax. Let’s take a look at how we might declare an active pattern.

Note: I will be using the sample from Active Patterns (F#)

So, this is the syntax for declaring an active pattern. The Microsoft documentation states the (| .. |) brackets are known as banana clips. So we declare the types within the banana clips and separated by the | operator, such as

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

So you’ll notice that the syntax does not include a function name, but only declares the type that the code can be matched against. Here’s an example of using this code within a pattern match

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

Now what happens is – when the function test is called with an input, for example

test 2     // this will output 2 is even

The line below the match tells F# to find the code which matches against a type Even or type Odd and run it. So in this case it will output 2 is even if we had executed the same code with the int 3 Odd would be returned from the active pattern and obvious 3 is odd will be output.

An extremely useful post on how the code can be viewed is on F Sharp Programming/Active Patterns.

To save time I’ll recreate the code here – so the declaration for the active patterns can be viewed as

type oddOrEven =
    | Even
    | Odd
 
let getChoice input = if input % 2 = 0 then Even else Odd