ClojureScript、Elm、PureScript、GHCJS 等不可变语言如何编译为可变语言 javascript?

How do immutable languages like ClojureScript, Elm, PureScript, GHCJS compile to mutable javascript?

我认为埋没所列语言的源代码对我来说太多了。但是有没有人能简单的解释一下事情是怎么发生的呢?

我的意思是,最终不可变数据仍然是javascript的数据。或者编译后的代码是否包含非标准数据结构,例如'a,b,c' 不可变数组的字符串

我会回复 PureScript,因为我对这门语言比较熟悉。

PureScript By Example [2.7] 关于 PureScript 到 JavaScript 一代:

  • Every module gets turned into an object, created by a wrapper function, which contains the module’s exported members.
  • PureScript tries to preserve the names of variables wherever possible.
  • Function applications in PureScript get turned into function applications in JavaScript.
  • The main method is run after all modules have been defined, and is generated as a simple method call with no arguments.
  • PureScript code does not rely on any runtime libraries. All of the code that is generated by the compiler originated in a PureScript module somewhere which your code depended on.

These points are important, since they mean that PureScript generates simple, understandable code. In fact, the code generation process in general is quite a shallow transformation. It takes relatively little understanding of the language to predict what JavaScript code will be generated for a particular input.

因此,是的,如您所写:"in the end immutable data will still be a javascript's data"。编译后,通过PureScript模块的包装函数在更高层次上保证了不变性。

PureScript 有 JavaScript 的字符串、数字和布尔值,它们已经是不可变的。最重要的是,PureScript 有 Array 和 Object,但只公开了某些操作。

当您在 PureScript 中更新一个对象时,您正在复制除了您更新的字段之外的字段。

连接数组的作用类似于:

function concatArray (xs) {
  return function (ys) {
    if (xs.length === 0) return ys;
    if (ys.length === 0) return xs;
    return xs.concat(ys);
  };
};

PureScript 有额外的定义数据的方法,这些(通常)编译成对象但也不会公开改变它们的方法。

但是使用 FFI 可以编写改变所有 PureScript 数据的代码。编写 FFI 绑定时必须小心。