
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 itDiscriminated unions
- OCaml calls itVariants
- TypeScript calls itTagged Union Types some times, and other times discriminated unions
- Haskell calls itAlgebraic 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#:
typeAnswer=Yes|Noletresponseanswer=matchanswerwith|Yes->"Correct answer"|No->"Wrong answer"
One popular example in OOP is to show inheritance with aShape
class. Here is an example but with discriminated unions instead:
typeShape=|Circleoffloat|Rectangleoffloat*float|SquareoffloatletcalculateAreashape=matchshapewith|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)
For further actions, you may consider blocking this person and/orreporting abuse