F Sharp Pattern Matching - F Sharp (programming language)

What is F# - Pattern Matching?

Pattern matching allows you to “compare data with a logical structure or structures, decompose data into constituent parts, or extract information from data in various ways”.

In other terms, it provides a more flexible and powerful way of testing data against a series of conditions and performing some computations based on the condition met.

Conceptually, it is like a series of if… then statements.

Syntax

In high level terms, pattern matching follows this syntax in F# −

Where,

  • Each | symbol defines a condition.
  • The -> symbol means "if the condition is true, return this value...".
  • The _ symbol provides the default pattern, meaning that it matches all other things like a wildcard.

Example 1

The following example, calculates the Fibonacci numbers using pattern matching syntax −

On compiling and and executing the program, it produces the below result

You can also chain together multiple conditions, which return the same value. For example −

Example 2

On compiling and and executing the program, it produces the below result

Pattern Matching Functions

F# allows you to write pattern matching functions using the function keyword −

On compiling and and executing the program, it produces the below result

Adding Filters or Guards to Patterns

You can add filters, or guards, to patterns using the when keyword.

Example 1

On compiling and and executing the program, it produces the below result

Example 2

On compiling and and executing the program, it produces the below result

Pattern Matching with Tuples

The following example demonstrates the pattern matching with tuples −

On compiling and and executing the program, it produces the below result

Pattern Matching with Records

The following example demonstrates pattern matching with records −

On compiling and and executing the program, it produces the below result

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

F Sharp (programming language) Topics