Feeding a function result into a pattern matching function in F#

Say we have an F# function that returns a tuple of two elements:

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. Here’s how we can consume this function:

let isGreaterThan x y =     
    if x > y then (true, x - y)
    else (false, 0)
    
let (gt, diff) = isGreaterThan 10 6
printfn "Is greater: %b, diff: %i" gt diff

…which prints “Is greater: true, diff: 4” in the interactive window. We can feed the result into a pattern matching expression and branch our logic as follows:

isGreaterThan 19 6 |> function
    | (true, diff) -> printfn "Difference: %i" diff
    | (false, diff) -> printfn "Less then"

The pattern matching expression is introduced by the function keyword followed by pattern matching logic. The above program prints “Difference: 13” in the interactive window.

The pattern matching branches must be exhaustive so the following would not be sufficient:

isGreaterThan 19 6 |> function
    | (true, diff) -> printfn "Difference: %i" diff

The code still runs but we get a warning: Incomplete pattern matches on this expression. For example, the value ‘(false,_)’ may indicate a case not covered by the pattern(s).

We get an exception in case there’s no matching pattern branch:

isGreaterThan 6 19 |> function
    | (true, diff) -> printfn "Difference: %i" diff

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

View all F# related articles here.

Advertisement

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: