向F#判别并集添加常量字段

向F#判别并集添加常量字段,f#,playing-cards,discriminated-union,F#,Playing Cards,Discriminated Union,是否可以将常量字段值添加到F#判别并集 我可以这样做吗 type Suit | Clubs("C") | Diamonds("D") | Hearts("H") | Spades("S") with override this.ToString() = // print out the letter associated with the specific item end 如果我正在编写Java枚举,我会向构造函数添加一个私有值,如下所示: pub

是否可以将常量字段值添加到F#判别并集

我可以这样做吗

type Suit
  | Clubs("C")
  | Diamonds("D")
  | Hearts("H")
  | Spades("S")
  with
    override this.ToString() =
      // print out the letter associated with the specific item
  end
如果我正在编写Java枚举,我会向构造函数添加一个私有值,如下所示:

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;
  }
}

当然不能,但是编写一个模式匹配的函数,然后组合这两件事是很简单的

最符合您需求的是:

F#enum的问题是非穷举模式匹配。在操作枚举时,必须使用通配符(
\uu
)作为最后一个模式。因此,人们倾向于选择有歧视的联合,并编写显式的
ToString
函数

另一个解决方案是在构造函数和相应的字符串值之间进行映射。如果我们需要添加更多构造函数,这将非常有用:

type SuitFactory() =
    static member Names = dict [ Clubs, "C"; 
                                 Diamonds, "D";
                                 Hearts, "H";
                                 Spades, "S" ]
and Suit = 
  | Clubs
  | Diamonds
  | Hearts
  | Spades
  with override x.ToString() = SuitFactory.Names.[x]

为了完整性,这就是其含义:

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

如何不通过FSI的第一个示例。| Diamonds='D'->| value1=integer-literal1'D'对于F#2.0,F#2.0 bug来说是错误的literall?
type Suit = 
  | Clubs
  | Diamonds
  | Hearts
  | Spades
  with
    override this.ToString() =
        match this with
        | Clubs -> "C"
        | Diamonds -> "D"
        | Hearts -> "H"
        | Spades -> "S"