【问题标题】:Combine multiple variants into one variant将多个变体组合成一个变体
【发布时间】:2018-06-10 06:16:49
【问题描述】:

有没有办法将多个变体组合成一个?像这样的:

type pet = Cat | Dog;
type wild_animal = Deer | Lion;
type animal = pet | wild_animal;

这是一个语法错误,但我希望 animal 成为具有四个构造函数的变体:Cat | Dog | Deer | Lion。有没有办法做到这一点?

【问题讨论】:

    标签: types ocaml variant reason


    【解决方案1】:

    多态变体的创建完全符合您的想法。它们作为内存表示的效率较低,但您是否要将其编译为 JavaScript 并不重要:

    type pet = [ | `Cat | `Dog];
    type wild_animal = [ | `Deer | `Lion];
    type animal = [ pet | wild_animal ];
    

    【讨论】:

    • 您的第一段错误:type t = Cat type w = Cat 在同一模块中完全有效。此外,无参数构造函数在运行时表示为简单的整数。
    • 好吧,刚刚删除了第一段,因为另一个答案解释得更好。
    • 我不认为多态变体效率较低。他们只是使用哈希值而不是从 0 开始计数。但大多数情况下,如果您使用 {0, 1, 2, 3} 或 {45346, 464575678, 6354645674, 32542} 作为变量的值,则没有区别。
    • 当您不使用具有多态变体的参数时,情况确实如此。当你这样做时,这会改变:dev.realworldocaml.org/…
    【解决方案2】:

    我希望animal变成一个有四个构造函数的变体:Cat |狗 |鹿 |狮子。有没有办法做到这一点?

    你不能直接这样做。这意味着Catpet 类型,但也有wild_animal 类型。使用通常只有一个类型的普通变体是不可能的。然而,正如另一个答案所描述的,这对于多态变体是可能的。

    另一种更常见的解决方案(但这取决于您要实现的目标)是定义第二层变体:

    type pet = Cat | Dog
    type wild_animal = Deer | Lion
    type animal = Pet of pet | Wild_animal of wild_animal
    

    这样,Cat 的类型为 pet,但 Pet Cat 的类型为 animal

    【讨论】:

    • 聪明啊!对于那些不熟悉常规 ocaml 语法的人,最后一条语句是type animal = Pet(pet) | Wild_animal(wild_animal) in reason
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2023-03-06
    相关资源
    最近更新 更多