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:
- F# calls it Discriminated unions
- OCaml calls it Variants
- TypeScript calls it Tagged Union Types some times, and other times discriminated unions
- Haskell calls it Algebraic data types
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"
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
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)