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!

Top comments (0)