pufuwozu/roy — Issue #71: Evaluate expression to be matched once only
Author: eegg
Created: 2011-12-13 00:14:36+00:00
State: open

Given the Roy code

```haskell

data Foo = Bar | Baz

let expensive n =
if n == 0 then
Bar
else
expensive (n - 1)

let foo = match (expensive 100000000000000)
case Bar = true
case Baz = false
```

I get (0.1.3) the compiled JS

```javascript
var Bar = function(){};
var Baz = function(){};
var expensive = function(n) {
return (function() {
if(n == 0) {
return new Bar();
} else {
return expensive(n - 1);
}
})();
}
var foo = (function() {
if(expensive(100000000000000) instanceof Bar) {
return true;
} else if(expensive(100000000000000) instanceof Baz) {
return false;
}
})();
```

This should clearly be evaluated once — firstly correctness if the expression is non-pure, and second for efficiency. That is, it should generate something like

```javascript
var Bar = function(){};
var Baz = function(){};
var expensive = function(n) {
return (function() {
if(n == 0) {
return new Bar();
} else {
return expensive(n - 1);
}
})();
}
var foo = (function() {
var tmp = expensive(100000000000000);
if(tmp instanceof Bar) {
return true;
} else if(tmp instanceof Baz) {
return false;
}
})();
```