如果我有一个带有多个值的有区别的联合共享一个子代(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"发布于 2017-01-23 21:22:06
我不认为使用单一模式可以很好地做到这一点,但你可以定义一个活动模式,它将为你提供两种苹果合并的数据的另一种视角:
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"发布于 2017-01-23 21:20:03
这个怎么样?
let speakFruit = function
| Apple x | MoreApples x ->
match x with
| GrannySmith -> "Granny Smith"
| Gala -> "gala"
| Banana -> "banana"发布于 2017-01-23 21:37:05
部分活动模式也可以是一种解决方案
let (|IsKind|_|) kind z =
match z with
| Apple x | MoreApples x -> if (kind = x) then Some true else None
| _ -> None
let speakFruit x =
match x with
| IsKind GrannySmith z -> "Granny Smith"
| IsKind Gala z -> "Gala"
| Banana -> "banana"
| _ -> "something else"但老实说,我同意Fyodor上面的观点。你可能应该重新考虑你的类型。
https://stackoverflow.com/questions/41807027
复制相似问题