【问题标题】:Is there a way to get the tag of a polymorphic variant as a variable in ReasonML有没有办法在 ReasonML 中获取多态变体的标签作为变量
【发布时间】:2018-04-26 20:03:29
【问题描述】:

我正在寻找是否可以将以下代码泛化一下。

type recordType = [
  | `Todo(todo, idFunction)
  | `TodoItem(todoItem, idFunction)


let commitItemToSchema = (normalizedSchema, recordType) => {
  switch(recordType){
  | `Todo    (todo,     idFun) => {...normalizedSchema, todo:       addOrModifyById(normalizedSchema.todo,       todo,       idFun)}
  | `TodoItem(todoItem, idFun) => {...normalizedSchema, todoItem:   addOrModifyById(normalizedSchema.todoItem,   todoItem,   idFun)}
  };
};

有没有办法可以从变体中获取\'Todo 或'TodoItem 作为变量?

谢谢

【问题讨论】:

  • 您能提供代码示例中显示的所有内容的类型吗?

标签: generics polymorphism variant reason


【解决方案1】:

如果您向我们展示了完整的类型集,将会很有帮助。 OCaml/BuckleScript/ReasonML 确实支持多态类型。这是在 ReasonML 中使用多态类型的简单类型和值声明。

type wrapper('a) = {
  item: 'a,
  details: string
};

let x = {item: 1, details: "This is an int"};

这里有两种函数,它们将wrapper 与无限制类型'a 和wrapper 与受限类型'a 作为int。

let unrestrictedType = (x: wrapper('a)) => {
  Js.log(x);
};

let restrictedType = (x: wrapper(int)) => {
  Js.log(x);
};

【讨论】:

    【解决方案2】:

    如果变体可以作为变量传递,在这种情况下它会丢失类型检查。我不认为 ReasonML 支持这一点。

    【讨论】:

      猜你喜欢
      • 2011-08-27
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      相关资源
      最近更新 更多