You could also use the binding mechanism that js functions have to swap the context they are ran in, although I’m not sure if it’s going to be faster than the two options already provided above.

function f_unbound(x) { return (x + this.y); }

const env = { y: 1 };
const f = f_unbound.bind(env);
f(1) // 2
mån 15 jan. 2018 kl. 11:35 skrev Leo White <leo@lpw25.net>:
> The best we could do (without doing some magic) would look like:
>
> let f x =
>   let y = x + 1 in
>   let g z = z + y in
>   g
>
> compiled to:
>
> function f_code(x, env) {
>   let y = x + 1;
>   function g_code(y, env) {
>     return(z + env.y);
>   }
>   let g = { code : g_code, env : { y: y };
>   return(g);
> }
>
> let f = { code : f_code, env : { } }

Pierre is right about the reason we don't use flambda with
bytecode, although I don't think that is the best JavaScript we
could produce.

It would not be to difficult to undo closure conversion within
the function body itself. This still leaves references to the
closure outside of the function body.  These aren't shown in
Pierre's example but they are produced during inlining and are
the main thing that flambda uses which bytecode doesn't
support. For these we can take advantage of the fact that
JavaScript functions are also ordinary objects, attaching the
environment to the function as fields:

    function f(x) {
      let y = x + 1;
      function g(z) {
        return(z + y);
      }
      g.y = y;
      return(g);
    }

Of course, this could still have an adverse effect on how the JIT
of different browsers deals with these functions, so some
benchmarking would be needed to confirm the viability of this
approach.

Regards,

Leo

--
Caml-list mailing list.  Subscription management and archives:
https://sympa.inria.fr/sympa/arc/caml-list
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs