Search code examples
f#playing-cardsdiscriminated-union

Adding constant fields to F# discriminated unions


Is it possible to add constant field values to F# discriminated unions?

Can I do something like this?

type Suit
  | Clubs("C")
  | Diamonds("D")
  | Hearts("H")
  | Spades("S")
  with
    override this.ToString() =
      // print out the letter associated with the specific item
  end

If I were writing a Java enum, I would add a private value to the constructor like so:

public enum Suit {
  CLUBS("C"),
  DIAMONDS("D"),
  HEARTS("H"),
  SPADES("S");

  private final String symbol;

  Suit(final String symbol) {
    this.symbol = symbol;
  }

  @Override
  public String toString() {
    return symbol;
  }
}

Solution

  • Just for completeness this is what is meant:

    type Suit = 
      | Clubs
      | Diamonds
      | Hearts
      | Spades
      with
        override this.ToString() =
            match this with
            | Clubs -> "C"
            | Diamonds -> "D"
            | Hearts -> "H"
            | Spades -> "S"