πRecap
Pattern matching
Fβ― core building block
Combines "data structure matching" and "deconstruction"
Used almost everywhere:
matchandfunctionexpressionstry/withblockletbinding, including function parameter
Can be abstracted into a
foldfunction associated with a union type
Patterns
Constant β’ Identifier β’ Wilcard
1, Color.Red β’ Some 1 β’ _
Collection : Cons β’ List β’ Array
head :: tail β’ [1; 2]
Product type : Record β’ Tuple
{ A = a } β’ a, b
Type Test
:? Subtype
Logical : OR, AND
1 | 2, P1 & P2
Variables β’ Alias
head :: _ β’ (0, 0) as origin
+ The when guards in match expressions
Active Patterns
Extending pattern matching
Based on function + metadata β first-class citizens
4 types: total simple/multiple, partial (simple), parametric
At first a little tricky to understand, but we get used to it quickly
Use for:
Add semantics without relying on union types
Simplify / factorize guards
Wrapping BCL methods
Extract a data set from an object
...
Addendum
π Match expressions, F# for fun and profit, 2012
π Domain modelling and pattern matching : Roman numeral, F# for fun and profit, 2012
π Recursive types and folds (6 articles), F# for fun and profit, 2015
Last updated
Was this helpful?