Ral*_*lph 6 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
Run Code Online (Sandbox Code Playgroud)
如果我正在编写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;
}
}
Run Code Online (Sandbox Code Playgroud)
为了完整性,这就是:
type Suit =
| Clubs
| Diamonds
| Hearts
| Spades
with
override this.ToString() =
match this with
| Clubs -> "C"
| Diamonds -> "D"
| Hearts -> "H"
| Spades -> "S"
Run Code Online (Sandbox Code Playgroud)
最接近您的要求的是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"
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
634 次 |
| 最近记录: |