Match expression
Similar to a switch
expression in C⯠8.0 but more powerful thanks to patterns
Syntax:
Returns the result of the 1st branch whose pattern "matches" test-expression
ā Note: all branches must return the same type!
Exhaustivity
A C# switch
must always define a default case.
Otherwise: compile warning, š„ MatchFailureException
at runtime
Not necessary in a F# match expression if branches cover all cases because the compiler checks for completeness and "dead" branches
ā Tip: the more branches are exhaustive, the more code is explicit and safe
Example: checking all the cases of a union type allows you to manage the addition of a case by a warning at compile time:
Warning FS0025: Special criteria incomplete in this expression
Detection of accidental addition
Identification of the code to change to handle the new case
Guard
Syntax: pattern1 when condition
Usage: to refine a pattern, using constraints on variables
š” The guard is only evaluated if the pattern is satisfied.
Guard vs OR Pattern
The OR pattern has a higher precedence/priority than the Guard :
Pattern composition
Pattern matching is powerful not only due to its exhaustivity but also because of the pattern composition.
ā Example:
Notes
This example demonstrates how we match the data on 4 levels:
feature
is a record with theValue
field (possibly amongst other fields)Value
has the caseBoolean
of the union typeFeatureValue
.This union case contains an optional boolean (
bool option
type).We detect when the provided value is
true
.
Match function
Syntax:
Equivalent to a lambda taking an implicit parameter which is "matched":
Benefits:
In a pipeline
Terser function
Example: a function with both explicit parameters and the function
keyword
ā The number of parameters and their order can be wrong:
Exhaustivity in OOP
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
ā It's FP in OOP, much very convoluted.
Last updated
Was this helpful?