pufuwozu/roy — Issue #74: Optimize tagged union of all nullary constructors
Author: eegg
Created: 2011-12-13 00:49:33+00:00
State: open

The following Roy

``haskell
data Bool =
True | False

let n b = match b
case True = False
case False = True
```

compiles (0.1.3) to

```javascript
var True = function(){};
var False = function(){};
var n = function(b) {
return (function() {
if(b instanceof True) {
return new False();
} else if(b instanceof False) {
return new True();
}
})();
}
```

It would be nice if this was optimized to, e.g.

```javascript
const True = 0; // Roy just picks ascending numbers from 0
const False = 1;
var n = function(b) {
return (function() {
if(b == 0) {
return 1;
} else if(b == 1) {
return 0;
}
})();
}
```

And in the particular case above of exactly two nullary data constructors for the type, we could optimize to booleans:

```javascript
const True = false; // Roy doesn't know of meaning, so assignment is arbitrary
const False = true;
var n = function(b) {
return (function() {
if(b == false) {
return true;
} else if(b == true) {
return false;
}
})();
}
```

Compiler flags could choose between

* just directly using the number/boolean representation
* using variables (`var`) to make compiled JS more readable
* using constants (`const`) instead, if desired