DEV Community

Cover image for Discriminated Unions
Stefan Alfbo
Stefan Alfbo

Posted on

Discriminated Unions

Discriminated unions are a powerful data structure to use when modelling a domain in an application.

The name of this data type varies between programming languages, for instance:

Pattern matching and discriminated unions are great together and makes it really easy to express complex models in the code.

Here is a simple example to make a boolish type in F#:

type Answer = Yes | No

let response answer =
    match answer with
    | Yes -> "Correct answer"
    | No -> "Wrong answer"
Enter fullscreen mode Exit fullscreen mode

One popular example in OOP is to show inheritance with a Shape class. Here is an example but with discriminated unions instead:

type Shape =
    | Circle of float
    | Rectangle of float * float
    | Square of float

let calculateArea shape =
    match shape with
    | Circle(radius) -> Math.PI * radius * radius
    | Rectangle(width, height) -> width * height
    | Square(side) -> side * side
Enter fullscreen mode Exit fullscreen mode

In other words:

Use discriminated unions for concise and type-safe representation of complex data structures, promoting clarity, pattern matching, and compiler-enforced correctness.

Happy hacking!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs