如果我有一个有多个值共享一个子项的可区分联合( Apple
和 MoreApples
都具有类型 Apple
)...
type Apples =
| GrannySmith
| Gala
type Fruit =
| Apple of Apples
| MoreApples of Apples
| Banana
let speakFruit = function
| Apple GrannySmith
| MoreApples GrannySmith -> "granny smith"
| Apple Gala
| MoreApples Gala -> "gala"
| Banana -> "banana"
有没有办法匹配子联合以消除重复? - 就像是:
let speakFruit2 = function
| _ GrannySmith -> "granny smith"
| _ Gala -> "gala"
| Banana -> "banana"
最佳答案
我认为使用单一模式没有什么好的方法可以做到这一点,但是您可以定义一个事件模式,该模式将为您提供合并两种苹果的数据的另一种视角:
let (|AnyApple|Banana|) = function
| Apple a | MoreApples a -> AnyApple a
| Banana -> Banana
这隐藏了标准
Banana
定义 - 您可能应该使用另一个名称以避免混淆,但其余的保持不变。现在您可以使用 AnyApple
进行模式匹配:let speakFruit = function
| AnyApple GrannySmith -> "granny smith"
| AnyApple Gala -> "gala"
| Banana -> "banana"
关于f# - 匹配受歧视 child 的工会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41807027/