puffnfresh / roy

Small functional language that compiles to JavaScript.
http://roy.brianmckenna.org/
MIT License
836 stars 74 forks source link

The subject of mach expression is evaluated multiple times. #135

Closed taku0 closed 11 years ago

taku0 commented 12 years ago

Sample Code

data Either a b =
  Left a | Right b

let f = \() ->
  console.log ":)"
  Right 1

match f()
  case (Left x) = console.log x
  case (Right x) = console.log x

Expected

:)
1

Actual

:)
:)
:)
1

Cause

The code is compiled into

...

(function() {
    if(f() instanceof Left) {
        var x = f()._0;
        return console.log(x);
    } else if(f() instanceof Right) {
        var x = f()._0;
        return console.log(x);
    }
})();

Thus, f() is evaluated multiple times.

Possible Fix

Compile the code into something like this:

...

(function(__tmp__) {
    if(__tmp__ instanceof Left) {
        var x = __tmp__._0;
        return console.log(x);
    } else if(__tmp__ instanceof Right) {
        var x = __tmp__._0;
        return console.log(x);
    }
})(f());