Google News
logo
F# - Interview Questions
What is an Pattern Matching in F#?
Patterns are rules for transforming input data. They are used throughout F# to compare data with a logical structure or structures, decompose data into constituent parts, or extract information from data in various ways.
 
Patterns are used in many language constructs, such as the match expression. They are used when you are processing arguments for functions in let bindings, lambda expressions, and in the exception handlers associated with the try...with expression. For more information, see Match Expressions, let Bindings, Lambda Expressions: The fun Keyword, and Exceptions: The try...with Expression.
 
For example, in the match expression, the pattern is what follows the pipe symbol.
match expression with
| pattern [ when condition ] -> result-expression
...
Each pattern acts as a rule for transforming input in some way. In the match expression, each pattern is examined in turn to see if the input data is compatible with the pattern. If a match is found, the result expression is executed. If a match is not found, the next pattern rule is tested. The optional when condition part is explained in Match Expressions.
 
Supported patterns are shown in the following table. At run time, the input is tested against each of the following patterns in the order listed in the table, and patterns are applied recursively, from first to last as they appear in your code, and from left to right for the patterns on each line.

Name Description Example
Constant pattern Any numeric, character, or string literal, an enumeration constant, or a defined literal identifier 1.0, "test", 30, Color.Red
Identifier pattern A case value of a discriminated union, an exception label, or an active pattern case Some(x)

Failure(msg)
Variable pattern identifier a
as pattern pattern as identifier (a, b) as tuple1
OR pattern pattern1 | pattern2 ([h] | [h; _])
AND pattern pattern1 & pattern2 (a, b) & (_, "test")
Cons pattern identifier :: list-identifier h :: t
List pattern [ pattern_1; ... ; pattern_n ] [ a; b; c ]
Array pattern [| pattern_1; ..; pattern_n |] [| a; b; c |]
Parenthesized pattern ( pattern ) ( a )
Tuple pattern ( pattern_1, ... , pattern_n ) ( a, b )
Record pattern { identifier1 = pattern_1; ... ; identifier_n = pattern_n } { Name = name; }
Wildcard pattern _ _
Pattern together with type annotation pattern : type a : int
Type test pattern :? type [ as identifier ] :? System.DateTime as dt
Null pattern null null
Nameof pattern nameof expr nameof str
Advertisement