Active Patterns as .NET API wrappers
Active Patterns can be used to make calling some .NET API's feel more natural, particularly those that use an output parameter to return more than just the function return value.
For example, you'd normally call the
System.Int32.TryParse method as follows:
You can improve this a bit using pattern matching:
However, we can also define the following Active Pattern that wraps the
Now we can do the following:
Another good candidate for being wrapped in an Active Patterns are the regular expressions API's:
Active Patterns can be used to validate and transform function arguments
An interesting but rather unknown usage of Active Patterns in
F# is that they can be used to validate and transform function arguments.
Consider the classic way to do argument validation:
Typically we add code in the method to verify that arguments are correct.
Using Active Patterns in
F# we can generalize this and declare the intent in the argument declaration.
The following code is equivalent to the code above:
For the user of function
g there's no difference between the two different versions.
A concern is if Active Patterns adds performance overhead. Let's use
ILSpy to decompile
g to see if that is the case.
inline the Active Patterns adds no extra overhead compared to the classic way of the doing argument validation.
Active Patterns with parameters
Active patterns are just simple functions.
Like functions you can define additional parameters:
This can be used in a pattern matching this way:
Complete and Partial Active Patterns
There are two types of Active Patterns that somewhat differ in usage - Complete and Partial.
Complete Active Patterns can be used when you are able to enumerate all the outcomes, like "is a number odd or even?"
Notice the Active Pattern definition lists both possible cases and nothing else, and the body returns one of the listed cases. When you use it in a match expression, this is a complete match:
This is handy when you want to break down the input space into known categories that cover it completely.
Partial Active Patterns on the other hand let you explicitly ignore some possible results by returning an
option. Their definition uses a special case of
_ for the unmatched case.
This way we can match even when some cases cannot be handled by our parsing function.
Partial Active Patterns can be used as a form of testing, whether the input falls into a specific category in the input space while ignoring other options.
Simple Active Patterns
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
To define an active pattern that classifies numbers as positive, negative or zero:
This can then be used in a pattern matching expression:
This modified text is an extract of the original Stack Overflow Documentation created by following contributors
and released under CC BY-SA 3.0