immutabilityelmpurescriptghcjs

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


I think burying to the listed languages' source code is too much for me. But is there anyone able to explain in simple terms how does the thing happens?

I mean, in the end immutable data will still be javascript's data. Or is compiled code contains non-std data structures e.g. 'a,b,c' string for immutable array


Solution

  • PureScript has JavaScript's String, Number and Boolean, which are immutable already. On top of that, PureScript has Array and Object but only exposes certain operations.

    When you update an Object in PureScript, you're copying the fields except the one you update.

    Concatenating Arrays does something like:

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

    PureScript has extra ways of defining data, these (usually) compile down to Object but also don't expose ways of mutating them.

    But using the FFI it is possible to write code which mutates all of your PureScript data. You have to be careful when writing FFI bindings.