与受歧视儿童结合的匹配



如果我有一个具有共享一个子值的多个值的可区分联合(AppleMoreApples都有类型 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"

这个怎么样?

let speakFruit = function
| Apple x | MoreApples x -> 
    match x with
    | GrannySmith -> "Granny Smith"
    | Gala -> "gala"
| Banana -> "banana"

部分活动模式也可能是一个解决方案

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"

但老实说 - 我同意上面的费奥多尔。你可能应该重新考虑你的类型。

相关内容

  • 没有找到相关文章

最新更新