如何使用 OCaml/Reason 在模块中创建内部值

How to create internal value in a module using OCaml/Reason

我有以下模块:

type userBuilderType = {
  mutable name: string,
};

module BuilderPattern = {
  let builder () => {
    name: "",
  };
  let setName = fun name => builder.name = name;
  let getName = builder.name;
};

BuilderPattern.setName("Charles");
Js.log(BuilderPattern.getName);

它完成了以下任务:

  1. 为 setter 创建类型
  2. 用于设置+获取的builderName对象 另外我想:
  3. 能够在 getName 函数上使用 JS.log 检索名称

但是,在这种情况下,我返回以下错误:

This is: unit => userBuilderType But somewhere wanted: userBuilderType 

关于我如何正确设置 setter/getter 的任何建议都非常感谢。谢谢。

你问题中的代码有很多问题,其中有几个是纯语法问题。 github 代码更有意义,但您遇到的主要问题是您没有在任何地方创建数据实例。

我想这就是你想要的,构造一个实例并传递给 getter 和 setter:

type userBuilderType = {
  mutable name: string,
  mutable age: int,
  mutable phone: string,
  mutable address: string
};

module BuilderPattern = {
  let builder () => {
    name: "",
    age: 0,
    phone: "",
    address: ""
  };
  let setName builder name => builder.name = name;
  let getName builder => builder.name;
};

let myBuilder = BuilderPattern.builder ();

BuilderPattern.setName myBuilder "Charles";
Js.log(BuilderPattern.getName myBuilder);

但这似乎也是对您意图的有效解释,其中状态是全局保存的(这通常是一个非常非常糟糕的主意):

type userBuilderType = {
  mutable name: string,
  mutable age: int,
  mutable phone: string,
  mutable address: string
};

module BuilderPattern = {
  let builder = {
    name: "",
    age: 0,
    phone: "",
    address: ""
  };
  let setName name => builder.name = name;
  let getName () => builder.name;
};

BuilderPattern.setName "Charles";
Js.log(BuilderPattern.getName ());

在这两种情况下,问题归结为以各种方式将采用单个单位参数的函数与仅 let 绑定混淆。