F#亚型歧视性结合
我有这样一个DU:F#亚型歧视性结合,f#,F#,我有这样一个DU: type Food = | Beer | Bacon | Apple | Cherry type NonFruit = NonFruit type Fruit = Fruit type Food = | Beer of NonFruit | Bacon of NonFruit | Apple of Fruit | Cherry of Fruit 我想在DU-to标记中添加一个特征,以确定食物是否为水果。我首先想到的是这样的事情: type Food = | Beer |
type Food =
| Beer
| Bacon
| Apple
| Cherry
type NonFruit = NonFruit
type Fruit = Fruit
type Food =
| Beer of NonFruit
| Bacon of NonFruit
| Apple of Fruit
| Cherry of Fruit
我想在DU-to标记中添加一个特征,以确定食物是否为水果。我首先想到的是这样的事情:
type Food =
| Beer
| Bacon
| Apple
| Cherry
type NonFruit = NonFruit
type Fruit = Fruit
type Food =
| Beer of NonFruit
| Bacon of NonFruit
| Apple of Fruit
| Cherry of Fruit
然后是这样一种方法:
type Food =
| Beer
| Bacon
| Apple
| Cherry
type NonFruit = NonFruit
type Fruit = Fruit
type Food =
| Beer of NonFruit
| Bacon of NonFruit
| Apple of Fruit
| Cherry of Fruit
让水果检查器(我的食物:食物)=
给我的食物配上
| :? 非水果->否
| :? 水果->“是”
但是编译器对我大喊大叫:
类型“Food”没有任何适当的子类型,因此无法使用
作为源头
我处理问题的方法有误吗
谢谢您只需为此添加一个函数即可。如果要使其“接近”类型,请将其设为静态成员:
type Food =
| Beer
| Bacon
| Apple
| Cherry
static member IsFruit = function Beer | Bacon -> false | Apple | Cherry -> true
将DU案例视为构造器-将啤酒厂的名称传递给啤酒构造器是有意义的,但无论它是否是水果,都是一种静态质量,这是不合适的。或者,使用活动模式:
打印:
No
No
Yes
Yes
链接:“匹配”关键字需要替换为“函数”才能编译。的可能重复项