Introduction:
Pattern Matching is one of
the most important tools of F Sharp programming. It
allows a programmer to make different computations, depending on matching patterns. It
decomposes data structures into their component parts. It is similar to a if..else
or switch statement in C or C++. It allows the programmer to test a value against a series of conditions and extract information depending on which conditions match.
Syntax for Pattern Matching
match exp with
| pattern1 -> result
| pattern2 -> result
|------------------
|------------------
| _ -> default
Here match and with are keyword.
Each rule of match is represented by | followed by arrow (->). Like
| pattern1 -> result meaning - if pattern
is matched (condition is true) then return result. ( _ ) denotes the default
pattern.
Different Ways to Form Patterns:-
Constant Pattern:
Input is compared with Constant pattern like, numeric, character,
string constants. If matched, then the corresponding value is returned. Note here,
the type of literal must be same type of input. We write a simple program for
constant matching.
//Constant pattern
let cons n =
match n with
| 1 -> "One"
| 2 -> "Two"
| 3 ->
"Three"
| 4 ->
"Four"
| 5 ->
"Five"
for i
in 1..5 do
printfn "%s" (cons i)
Output:
Variable Pattern:
The variable pattern assigns the
matching value to a variable which is used as result.
let vari x =
match x
with
| (fisrt, second) when first > second
-> "first number is greater"
| (first, second) when first < second
-> "second number is greater"
| (first, second) ->
"both are equal"
printfn "%s" ( vari( 1 , 2) )



Join the conversation! Your thoughts help the community grow.