Using Pattern Matching
Pattern Matching is one of the fundamental concepts of functional programming.
This concept can be used to replace a lot of code flow structures, such as:
If-else statements
Switch-cases
Loops (for, foreach, while e do)
Types comparison
A pattern matching in the F# language to replace an if statement has a syntax similar to:
match boolExpression with
| true -> //pattern when true
| false -> //pattern when false
You can also using patterns to compare an int
value:
let value = 10
match value with
| 1 | 2 | 3 -> //When the value is 1, 2 or 3
| n when n % 2 = 0 -> //When the value is an even number
| 5 -> //When the value is equals to 5
| _ -> //Other cases
There are a lot of benefits to using pattern matching, so, from C# 7.0 version it is possible to use this feature natively in the language, according to the documentation of the Microsoft.
As an implementation in Tango library, some types have a method called Match
.
These methods receive lambda expressions for each pattern as a parameter, according to each type.
Besides that, there are also an implementation of a method called Match2
, similar to the previous one, but in this case, the patterns are applied to two different values simultaneously.
Last updated
Was this helpful?