3

我正在尝试组织和重用我的 reasonML 代码。我的模型模块类型如下所示:

module Diet = {

  type schemaType = [`DietSchema];
  type idType = [`DietId(UUID.t)];

  let schema = `DietSchema;
  type idAsType('a) = [> | idType] as 'a;     
};

module Ingredient = {
  type schemaType = [`IngredientSchema];
  type idType = [`IngredientId(UUID.t)];

  let schema = `IngredientSchema;
  type idAsType('a) = [> | idType] as 'a;
};

module Restriction = {
  type schemaType = [`RestrictionSchema];
  type idType = [`RestrictionId(UUID.t)];

  let schema = `RestrictionSchema;
  type idAsType('a) = [> | idType] as 'a;
};

我想从idTypes 和schemaTypes 生成一个类型和函数。

例子是:

type modelIdType = [
  | Diet.idType
  | Restriction.idType
  | Ingredient.idType
];

type schemaType = [
  | Diet.schemaType
  | Restriction.schemaType
  | Ingredient.schemaType
];

let modelIdToIdFunction = (recordIdType): (schemaType, UUID.t) =>
  switch (recordIdType) {
  | `DietId(uuid) => (Diet.schema, uuid)
  | `RestrictionId(uuid) => (Restriction.schema, uuid)
  | `IngredientId(uuid) => (Ingredient.schema, uuid)
  };

所以我正在尝试使用函子来构造一个模块,将每个模式通过

module Diet : SchemaType = {
  /* ... */
};

module type SchemaType {
  type schemaType;
  type idType;

  let schema: [> schemaType];
  type idAsType('a) = [> | idType] as 'a;
};

module ProcessSchema = (
  Schema : SchemaType,
  PrevFullSchema : FullSchema
) : (FullSchema) => {
  type id = [> Schema.idType' | PrevFullSchema.id'('a)]  as 'a;
  /* type id = [PrevFullSchema.openId(PrevFullSchema.id) | Schema.idType]; */
  /* type schema = [PrevFullSchema.schema | Schema.schema]; */
  /* type openSchema = [PrevFullSchema.schema | Schema.schema]; */
};

上面的代码不起作用。我在将模块类型添加到顶部的模型模块时遇到问题。我也尝试过一个SchemaType模块类型,但一直在点击The type idType is not a polymorphic variant type,当我希望每个模型都有不同的多态变量类型时。

所以总的来说,我想知道是否可以创建一个可以使用模块和仿函数创建或扩展的多态变体类型?

如果不是,是否可以使用“模块列表”构造多态变体类型?

谢谢

4

2 回答 2

1

早在 2002 年就有人问过类似的问题。根据一位 OCaml 语言开发人员的说法,不可能像这样动态扩展多态变体类型:https ://caml-list.inria.narkive.com/VVwLM96e/module-types-和-多态-变体。相关位:

函子定义被拒绝,因为“类型 Mt 不是多态变体类型” 有解决方法吗?

不是我知道的。多态变体扩展仅适用于已知的封闭变体类型,否则将不合理。

这篇文章的其余部分有一个建议,归结为在不同的标签中捕获新的变体类型,但这同样不适用于您使用仿函数动态“添加”类型的用例。

于 2018-12-12T03:47:44.323 回答
0

对于这些类型,您可以使用可扩展的变体类型。但是对于给定模块列表的 modelIdToIdFunction 函数,我认为您只能在列表中进行搜索,这将无法扩展。

您应该使用每个模块的 ID 扩展 uuid,以便您可以创建一个从 module_id 到列表中的模块的查找表,以便快速访问。

于 2018-12-07T16:00:55.127 回答