Fsharp: Discriminated union
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
Circle,Rectangle, andPointare the cases.- You create a value with one case:
Circle 5.0orPoint. - You inspect it only by pattern matching (the compiler checks that you handle every case).
option itself is a discriminated union:
type Option<'T> = | None | Some of 'T
That’s why None and Some work the way they do.