Using Discriminated Union Labelled Fields

A few weeks ago, I re-discovered labelled fields in discriminated unions. Despite the fact that they look like tuples, they are not.

This is my entry to F# Advent Calendar 2021. Thanks to Sergey Tihon for organising the Advent Calendar each year.

A few weeks ago, I re-discovered labelled fields in discriminated unions:

// Without labels
type Customer =
    | Registered of string * string option * bool
    | Guest of string

// With labels
type Customer =
    | Registered of Name:string * Email:string option * IsEligible:bool
    | Guest of Name:string

I knew that the feature existed but I've usually built specific types, generally records, for each union case, so hadn't really used them in anger before. This isn't a new feature: Field labels in discriminated union case members were introduced in F# 3.1. Despite the fact that they look like tuples, they are not. For example, tuples in F# do not support labels like they do in C#.

In this post, we will look at how to make use of this feature.

Getting Started

We are going to start with a simple business feature:

(*
Feature: Applying a discount

Scenario: Eligible Registered Customers get 10% discount 
when they spend £100 or more

Given the following Registered Customers
|Customer Id|Email          |Is Eligible|
|John       |john@test.org  |true       |
|Mary       |mary@test.org  |true       |
|Richard    |               |false      |
|Alison     |alison@test.org|false      |

When  spends 
Then their order total will be 

Examples:
|Customer Id| Spend | Total |
|Mary       |  99.00|  99.00|
|John       | 100.00|  90.00|
|Richard    | 100.00| 100.00|
|Sarah      | 100.00| 100.00|
*)

We are going to create two functions: One to calculate the totals after discount and one to return the email address of eligible customers. Emails are mandatory for Eligible customers and optional for Registered customers.

Creating Labelled Fields

The type design used in this post is specifically designed for the task of discovering how we can work with labelled fields. We start with a simple discriminated union with two union cases:

type Customer =
    | Registered of Name:string * Email:string option * IsEligible:bool
    | Guest of Name:string

Pattern Matching on Labelled Fields

As they look like tuples, can we deconstruct them in a match expression in the same way without the labels? It turns out that you can:


 
let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (name, email, isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

In this case, I'm only interested in the IsEligible flag, so will wildcards work? Yes they do:

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (_, _, isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

Now let's try adding the labels in and get the values like we would with fields on a record type. Sadly, this doesn't work as we get a compiler error:

// Compiler Error
let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (Name = name, Email = email, IsEligible = isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

As I said earlier, they look like tuples but they aren't. The fix turns out to be simple: Replace the comma separators with semi-colons:

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (Name = name; Email = email; IsEligible = isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

As we are not using name and email, can we use wildcards to ignore their data? Yes we can:

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (Name = _; Email = _; IsEligible = isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

How about wildcards to ignore the fields? This change gives us a compiler error:

// Compiler Error
let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (_; _; IsEligible = isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

Again, the fix turns out to be simple: Remove the fields completely from the pattern match:

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (IsEligible = isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

That's better but it would be nice if we could apply a filter directly rather than having to get the value and then test it. We can do this with records and thankfully it is available here too:

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (IsEligible = true) when spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

We can also combine the filter and the value getter as shown in the following function where we filter on IsEligible and return the value of the Email field into a local binding:

let tryGetEligibleEmail customer =
    match customer with
    | Registered (IsEligible = true; Email = email) -> Some email 
    | _ -> None

In summary, we use ',' for separating the fields when we don't use the labels in the pattern match and ';' when we do. If we are not interested in a field, don't use it in the match. We can use filters and value getters in the same match.

Creating an Instance of a DU Case

You can create an instance of a union case without specifying the field labels:

// let john = Registered ( "John", Some "john@test.org", true )

Personally, I think it makes more sense to use the labels if you provided them in the first place:

let john = Registered ( Name = "John", Email = Some "john@test.org", IsEligible = true )
let mary = Registered ( Name = "Mary", Email = Some "mary@test.org", IsEligible = true )
let richard = Registered ( Name = "Richard", Email = None, IsEligible = false )
let alison = Registered ( Name = "Alison", Email = Some "alison@test.org", IsEligible = false )
let sarah = Guest ( Name = "Sarah" )

Verifying these the functions with the instances is trivial. Firstly, the calculateOrderTotal function:

let assertJohn = calculateOrderTotal john 100.0M = 90.0M
let assertMary = calculateOrderTotal mary 99.0M = 99.0M
let assertRichard = calculateOrderTotal richard 100.0M = 100.0M
let assertSarah = calculateOrderTotal sarah 100.0M = 100.0M

and then the tryGetEligibleEmail function:

let assertMaryEmail = tryGetEligibleEmail mary = Some "mary@test.org"
let assertRichardEmail = tryGetEligibleEmail richard = None
let assertAlisonEmail = tryGetEligibleEmail alison = None
let assertSarahEmail = tryGetEligibleEmail sarah = None

What Happens If ...

What happens if you decide not to include a label for the Name field?

type Customer =
    | Registered of string * Email:string option * IsEligible:bool
    | Guest of Name:string

The tuple-style pattern match with no labels works fine as does the version with the wildcards:

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (name, email, isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (_, _, isEligible) when isEligible && spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

Removing the label from the original version with labels causes a compiler error:

// Compiler Error
let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (name; Email = email; IsEligible = true) when spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

Removing that field and only using labelled fields works correctly:

let calculateOrderTotal customer spend =
    let discount = 
        match customer with
        | Registered (Email = email; IsEligible = true) when spend >= 100M -> spend * 0.1M 
        | _ -> 0M
    spend - discount

You don't have to supply every field with a label if you aren't going to pattern match on it with that label. I like consistency and would either supply labels to all fields or none at all.

Summary

I hope that you found this short post useful. Even if you decide not to use these features, it is still nice to know that they are available to you.
I have written an ebook called Essential Functional-First F#. All of the royalties go to the F# Software Foundation to support their promotion of the F# language and community around the world.

Follow me on Twitter at @ijrussell!

Blog 5/1/21

Ways of Creating Single Case Discriminated Unions in F#

There are quite a few ways of creating single case discriminated unions in F# and this makes them popular for wrapping primitives. In this post, I will go through a number of the approaches that I have seen.

Blog

Using AI correctly in 2025

The four biggest stumbling blocks for generative AI in 2025 - and how to avoid them.

Blog 3/17/22

Using NLP libraries for post-processing

Learn how to analyse sticky notes in miro from event stormings and how this analysis can be carried out with the help of the spaCy library.

Blog

Celebrating Homai - Using AI for Good

Our colleague Aigiz Kunafin has achieved an outstanding milestone - importance of his side-project Homai was acknowledged by the “AI for Good” Initiative of United Nations.

Blog 6/24/21

Using a Skill/Will matrix for personal career development

Discover how a Skill/Will Matrix helps employees identify strengths and areas for growth, boosting personal and professional development.

Process Integration & Automation
Service

Process Integration & Automation

Digitizing and improving business processes and reacting to changes in an agile way – these are the challenges that more and more companies need to face.

Security, Identity & Access Management
Service

Security, Identity & Access Management

Time and again we hear about hacker attacks on companies that target sensitive company data. Therefore, security and access control of data must never be neglected.

Managed Services & Managed Support
Service

Managed Services & Managed Support

Our Managed Service Team of specialists will relieve your IT department. We ensure that you can work more efficiently, reliably and quickly

Digital Workplace & Employee Experience
Service

Digital Workplace & Employee Experience

The Digital Workplace gained in importance, especially in recent months, becoming indispensable for many companies. The Microsoft Office 365 platform provides an ideal basis for this development.

Logo Microsoft
Technologie 6/29/20

Microsoft

We are Microsoft Gold Partner for Collaboration and Content. ▶ We combine the strengths and competencies of Microsoft and its partners. ✓

Unternehmen

Directions to TIMETOACT GROUP in Cologne

Whether you travel by car, train or plane, we will show you the best way to get to the Mediaparkt in Cologne.

Referenz

Consulting on the ivv collaboration strategy

The future collaboration of ivv is characterized by modern communication and collaboration tools. It is defined for cross-organizational work in association and with external parties.

Standort

Location in Cologne

Find us on site in Cologne: catworkx, CLOUDPILOTS, IPG, novaCapta, synaigy, TIMETOACT, X-INTEGRATE: Im Mediapark 5; 50670 Cologne, Germany

Google Logo
Technologie 6/29/20

Google

Google is more than Google Search and Google Ads! We advise you on Google Analytics, Google Cloud Platform, G Suite, Google Cloud IoT and more!

Articifial Intelligence & Data Science
Service

Artificial Intelligence & Data Science

Data Science is all about extracting valuable information from structured and unstructured data.

Analytics und Business Intelligence
Service

Analytics & Business Intelligence

Analytics & Business Intelligence has become increasingly important in recent years.

Logo RedHat
Technologie 7/2/20

RedHat

We are RedHat Advanced Partner. With RedHat as the market leader in Open Source IT solutions, we support our customers in actively designing and implementing their cloud journey.

Unternehmen

ARS Computer und Consulting GmbH

ARS is one of the leading companies in Software Engineering. For them, Cognitive Solutions and Artificial Intelligence are the future.

Software & Application
Service

Software & Application

Agility, Application Modernization, Fullstack Development and Requirement Engineering are important aspects of Business Application Development.

Unternehmen

CLOUDPILOTS Software & Consulting GmbH

CLOUDPILOTS consults and supports companies in the transformation process of business processes and applications to the Cloud. Also, it assists in the implementation of Cloud based IT services (SaaS).

Bleiben Sie mit dem TIMETOACT GROUP Newsletter auf dem Laufenden!