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

时间:2017-10-24 13:19:54

标签: ocaml mutable 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函数
  4. 上的JS.log检索名称

    但是,在这种情况下,我得到了以下错误:

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

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

1 个答案:

答案 0 :(得分:2)

您的问题中的代码存在许多问题,其中一些纯粹是语法问题。 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绑定混淆的函数以各种方式混淆。