Fsharp: Discriminated union

By Xah Lee. Date: .
work in progress

Discriminated union

what's discriminated union

(ai answer)

A discriminated union (DU) in F# is a type that can be exactly one of several named cases. Each case can optionally carry data.

They are the foundation of option, Result, and many other F# types.

Simple example

type Shape =
    | Circle of radius: float
    | Rectangle of width: float * height: float
    | Point

let area shape =
    match shape with
    | Circle r          -> System.Math.PI * r * r
    | Rectangle (w, h)  -> w * h
    | Point             -> 0.0

option itself is a discriminated union:

type Option<'T> =
    | None
    | Some of 'T

That’s why None and Some work the way they do.