Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Discriminated Unions
Stefan Alfbo
Stefan Alfbo

Posted on

Discriminated Unions

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:

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"
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software developer that is passionate about learning new technologies and solving complex problems. Always trying to be curious and open minded to improve my skills.
  • Location
    Sweden
  • Education
    KTH Royal Institute of Technology
  • Work
    Software developer
  • Joined

More fromStefan Alfbo

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp