gpt4 book ai didi

f# - 向 F# 可区分联合添加常量字段

转载 作者:行者123 更新时间:2023-12-04 13:33:49 24 4
gpt4 key购买 nike

是否可以将常量字段值添加到 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 枚举,我会向构造函数添加一个私有(private)值,如下所示:
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;
}
}

最佳答案

只是为了完整起见,这意味着:

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

关于f# - 向 F# 可区分联合添加常量字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10383858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com