A neat trick I noticed while watching the Dungeons, Dragons and Functions talk by Mathias Brandewinder is adding overloads to a discriminated union.
In his talk, he is modelling Dungeons and Dragons using F#. One of the things he needs to model is a dice roll. In D&D you have uncommon dice shapes and inside the rule book you’ll find dice rules like: 4d6+2d10+8
.
What does this formula means? 4 roles of a 6-sided dice + 2 roles of a 10-sided dice+ 8
To model this in F#, Mathias created the following discriminated union:
You can then use this Roll type to create the formula above:
This works but is not very readible. To fix this, Mathias introduced some overloads on the Roll type:
This nicely cleans up the formula to:
More information can be found in Mathias blog post here: https://brandewinder.com/2018/07/31/give-me-monsters-part-3/