Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
}
like image 899
Ralph Avatar asked Apr 30 '12 12:04

Ralph


1 Answers

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"
like image 171
yamen Avatar answered Sep 17 '22 16:09

yamen