Rob*_*obz 4 ocaml types variant reason
有没有办法将多个变体组合成一个?像这样的东西:
type pet = Cat | Dog;
type wild_animal = Deer | Lion;
type animal = pet | wild_animal;
Run Code Online (Sandbox Code Playgroud)
这是一个语法错误,但我希望动物成为一个有四个构造函数的变体:Cat | Dog | Deer | Lion.有没有办法做到这一点?
多态变体的创建完全符合您的想法.它们作为内存表示的效率较低,但是如果要将其编译为JavaScript则无关紧要:
type pet = [ | `Cat | `Dog];
type wild_animal = [ | `Deer | `Lion];
type animal = [ pet | wild_animal ];
Run Code Online (Sandbox Code Playgroud)
我想动物成为一个有四个构造函数的变体:Cat | 狗| 鹿| 狮子.有没有办法做到这一点?
你不能直接这样做.这意味着Cat有类型pet,但也类型wild_animal.使用常规变体是不可能的,它们总是只有一种类型.然而,正如另一个答案所描述的那样,这可能是多态变体.
另一种解决方案,更常见(但取决于您要实现的目标),是定义第二层变体:
type pet = Cat | Dog
type wild_animal = Deer | Lion
type animal = Pet of pet | Wild_animal of wild_animal
Run Code Online (Sandbox Code Playgroud)
那样,Cat有类型pet,但Pet Cat有类型animal.
| 归档时间: |
|
| 查看次数: |
231 次 |
| 最近记录: |