Match expression
Similar to a switch expression in Cβ― 8.0 but more powerful thanks to patterns
Syntax:
match test-expression with
| pattern1 [ when condition ] -> result-expression1
| pattern2 [ when condition ] -> result-expression2
| ...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
let fn x =
match x with
| Some true -> "ok"
| Some false -> "ko"
| None -> ""
| _ -> "?"
// ~ β οΈ Warning FS0026: his rule will never be matchedβ 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:
featureis a record with theValuefield (possibly amongst other fields)Valuehas the caseBooleanof the union typeFeatureValue.This union case contains an optional boolean (
bool optiontype).We detect when the provided value is
true.
Match function
Syntax:
Equivalent to a lambda taking an implicit parameter which is "matched":
Benefits:
In pipelines
More concise function
Limitations
As the parameter is implicit, it can make the code more difficult to understand! β See Point-free style
Example: a function with both explicit parameters and the function keyword
β The number of parameters and their order can be wrong:
Exhaustivity in OOP
The equivalent of the pattern matching exhaustivity in FP is ... the Visitor design pattern 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?