Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 1784

Question about variables in module behavior

$
0
0

The reason you are seeing this is because of JavaScript. Here’s the compiled JS from what you wrote:

// Generated by ReScript, PLEASE EDIT WITH CARE

let state = [];

function make(foo) {
  state.push(foo);
  return state;
}

let MyModule = {
  state: state,
  make: make
};

let a1 = make("a");

let _a2 = make("b");

console.log(a1);

export {
  MyModule,
  a1,
  _a2,
}
/* a1 Not a pure module */

OCaml behaves differently because Modules are represented differently in the runtime. ReScript and Melange are compiling to JS, so you will see the same results.

If you want state to be unique to each call for make you would need to make sure it’s part of the closure for the make function, which keeps it isolated to only that function.

module MyModule = {
  type t = array<string>

  let make = (foo: string): t => {
    let state: t = []
    state->Array.push(foo)
    state
  }
}

Viewing all articles
Browse latest Browse all 1784

Trending Articles