# Basic pattern matching in F#

May 20, 2017 2 Comments

Pattern matching in F# is somewhat similar to switch blocks in C#. However, pattern matching blocks can provide much more complex branching logic than switch blocks.

Consider the following F# function:

let isGreaterThan x y = if x > y then (true, x - y) else (false, 0)

…, i.e. we return true and the difference between the two input integers if the first integer is greater. Otherwise we return a false and a 0. In other words the return type is a tuple with two elements, a boolean and an integer.

The pattern matching logic must take into account of all possible branches, i.e. there must be a branch for each of the possible outcomes from the function. Here’s an example of how a tuple with a boolean and an integer can be analysed in a pattern matching function:

let analyseGreaterThan outcome = match outcome with | (true, diff) -> printfn "Difference: %i" diff | (false, diff) -> printfn "Less then"

“outcome” will be an input parameter into the analyseGreaterThan function. Its value will be matched against the branching logic in the “with” block. We have at least two possibilities: one where the boolean is true and another where it is false. These are the two branches we need to account for otherwise we’ll get a compile time warning:

Incomplete pattern matches on this expression. For example, the value ‘(false,_)’ may indicate a case not covered by the pattern(s).

Here’s how we can call the pattern matching function:

let res = isGreaterThan 10 6 analyseGreaterThan res

“res” will evaluate to a tuple of true and 4 hence the first branch of the pattern matching logic will be executed.

If we comment out the second pattern matching branch and call the function as follows…

let res = isGreaterThan 4 6 analyseGreaterThan res

…then we get an exception:

Microsoft.FSharp.Core.MatchFailureException: The match cases were incomplete

View all F# related articles here.

Pingback: F# Weekly #21, 2017 – Welcome new FSSF board! – Sergey Tihon's Blog

Pingback: Pattern matching in C# 7.0 | Fitness Promotions