DEV Community

Discussion on: When to use a Discriminated Union vs Record Type in F#

Collapse
 
alexanderlindsay profile image
Alexander Lindsay • Edited

This is a good explanation of the two types.

Both types are very useful on there own, but things get interesting when you combine them. Also, there are choices for how to combine them.

For example, in a card game of sorts is there a record type Card that has a discriminated union CardType or does the union contain the records?

See the following:

type CardType
| Attack of int
| Defense of int

type Card = {
  cost: int;
  type: CardType;
}
Enter fullscreen mode Exit fullscreen mode

or

type AttackCard =
{
  strength: int;
  cost: int;
}

type DefenseCard =
{
  mitigation: int;
  cost: int;
}

type Card
| Attack of AttackCard
| Defense of DefenseCard
Enter fullscreen mode Exit fullscreen mode

I think it depends on how the cards are going to be used. If the second pattern is followed then every interaction with a card will first have to handle the card type. If you need the cost before the type something like the first pattern should work.

Collapse
 
josegonz321 profile image
Jose Gonzalez

Excellent example. You are right, it depends how you are going to use your cards.

There is no silver bullet but it's always good to know that there are options available.

Thank you for sharing your thoughts on this.