【问题标题】:Adding constant fields to F# discriminated unions向 F# 可区分联合添加常量字段
【发布时间】:2012-05-10 03:54:44
【问题描述】:

是否可以向 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# playing-cards discriminated-union


    【解决方案1】:

    很确定你不能,但是编写一个模式匹配的函数然后组合这两个东西是微不足道的

    【讨论】:

      【解决方案2】:

      最接近您要求的是F# enums

      type Suit =
          | Diamonds = 'D'
          | Clubs = 'C'
          | Hearts = 'H'
          | Spades = 'S'
      
      let a = Suit.Spades.ToString("g");;
      // val a : string = "Spades"
      
      let b = Suit.Spades.ToString("d");; 
      // val b : string = "S"
      

      F# 枚举的问题在于非详尽的模式匹配。在操作枚举时,您必须使用通配符 (_) 作为最后一个模式。因此,人们往往更喜欢有区别的联合,并编写显式的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]
      

      【讨论】:

      • 第一个不通过FSI的例子。
      • |钻石 = 'D' -> | value1 = integer-literal1 'D' bad literall for F# 2.0 , F#2.0 bug?
      【解决方案3】:

      为了完整起见,这是什么意思:

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

      【讨论】:

        猜你喜欢
        • 2011-11-19
        • 1970-01-01
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        • 2014-09-13
        • 2012-12-14
        相关资源
        最近更新 更多