Discriminated unions (sum types) in F# programming language

22 Aug 2023 Sejal Sah 0 F# programming language

Exploring Discriminated Unions (Sum Types) in F# Programming

Discriminated unions, also known as sum types or algebraic data types, are a powerful feature in functional programming languages like F#. They allow you to define a type that can hold one of a set of named values (constructors), each with potentially different associated data. This is particularly useful for modeling data structures that have multiple possible shapes.

In F#, you can define a discriminated union using the type keyword, followed by the union name and a set of constructors.

Here's a simple example:

fsharp
type Shape =
    | Circle of float // Constructor with associated data
    | Rectangle of float * float // Constructor with two associated data values
    | Triangle of float * float * float // Constructor with three associated data values

In this example, we've defined a discriminated union named Shape with three constructors: Circle, Rectangle, and Triangle. Each constructor can hold a different number of associated data values.

You can create instances of these union types by using the constructors:

fsharp
let circle = Circle(5.0)
let rectangle = Rectangle(3.0, 4.0)
let triangle = Triangle(3.0, 4.0, 5.0)

To perform pattern matching on discriminated unions, you can use the match expression:

fsharp
let area shape =
    match shape with
    | Circle(radius) -> Math.PI * radius * radius
    | Rectangle(width, height) -> width * height
    | Triangle(a, b, c) ->
        let s = (a + b + c) / 2.0
        sqrt(s * (s - a) * (s - b) * (s - c))

In this example, the area function takes a Shape and matches it against the constructors to calculate the area based on the shape's characteristics.

Discriminated unions are a versatile tool for modeling complex data structures and representing different cases or scenarios in your code. They promote robustness by forcing you to handle all possible cases explicitly, making your code less error-prone.

BY: Sejal Sah

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.