Basic pattern matching in F#

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.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Basic pattern matching in F#

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

  2. Pingback: Pattern matching in C# 7.0 | Fitness Promotions

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: