繁体   English   中英

F#Subtype Disriminated Unions

[英]F# Subtype Discriminated Unions

我有这样的DU:

type Food =
| Beer
| Bacon
| Apple
| Cherry

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

type NonFruit = NonFruit
type Fruit = Fruit

type Food =
| Beer of NonFruit
| Bacon of NonFruit
| Apple of Fruit
| Cherry of Fruit

然后像这样的方法:

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

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

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

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

谢谢

或者,使用活动模式: 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))

打印:

No
No
Yes
Yes

链接: https//dotnetfiddle.net/oRYDs6

你应该简单地添加一个函数。 如果要使其“接近”类型,请将其设为静态成员:

type Food =
   | Beer
   | Bacon
   | Apple
   | Cherry
   static member IsFruit = function Beer | Bacon -> false | Apple | Cherry -> true

将DU案例视为构造函数 - 将啤酒厂的名称传递给Beer构造函数是有意义的,但无论它是否为水果都是静态质量,在那里是不合适的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM