F#Subtype Disriminated Unions

Jam*_*xon 4 f#

我有这样的DU:

type Food =
| Beer
| Bacon
| Apple
| Cherry
Run Code Online (Sandbox Code Playgroud)

如果食物是水果,我想给DU添加一个特征来标记.我首先想到的是这样的事情:

type NonFruit = NonFruit
type Fruit = Fruit

type Food =
| Beer of NonFruit
| Bacon of NonFruit
| Apple of Fruit
| Cherry of Fruit
Run Code Online (Sandbox Code Playgroud)

然后像这样的方法:

让fruitChecker(myFood:Food)=将myFood与|匹配 :?NonFruit - >"不"| :?水果 - >"是"

但是编译器对我大喊大叫:

"食物"类型没有任何正确的子类型,不能用作来源

我是否错误地接近了这个问题?

谢谢

Rei*_*ica 9

或者,使用活动模式:https://msdn.microsoft.com/en-us/library/dd233248.aspx

type Food =
| Beer
| Bacon
| Apple
| Cherry

let (|NonFruit|Fruit|) =
    function
    | Beer | Bacon -> NonFruit
    | Apple | Cherry -> Fruit

let fruitChecker = function | NonFruit -> "No" | Fruit -> "Yes"

[Beer;Bacon;Apple;Cherry] |> List.iter(fun x -> printfn "%s" (fruitChecker x))
Run Code Online (Sandbox Code Playgroud)

打印:

No
No
Yes
Yes
Run Code Online (Sandbox Code Playgroud)

链接:https://dotnetfiddle.net/oRYDs6