Tuple with unpack alternative

In rust everything is an expression goes in harmony with tuple and multple assign for example.

let (location,timezone)=if is_us {
 ("NEW YORK","EST")
} else {
("PARIS","CET")
}

combine that with switch…

compared to the following javascript.

if (is_us){
//var leaks out of scope in javascript
var location="NEW YORK";
var tz="EST"
} else {
var location="PARIS";
var tz="CET";
}

This is very importent because the rust checker will make you sick and give you no other way of getting the variables in the global scope (I do not remeber exactly the details, I dropped rust a while ago, but decalring upwards and modifying in the inner scope made some limitations.)

In haxe var will not leak, so we cannot directly use the js code, but we could declare the variables earlier, but in turn we lose branch protecting.

var location="";
var tz="";
if (is_us){
location="NEW YORK";
tz="EST"
} else {
location="PARIS";
tz="CET";
}

I am constantly finding myself with this inconveniance, I made once a macro that takes the if statement as parameter, the list of params, and it does the code generation and merges the scopes, but its not pretty, no intellisense and allocates a temporary array in the resulting code.

What is the correct approach here?

Thanks for any advice

Maybe you should try abstract here like this Try Haxe!

What’s wrong with this?

typedef TS = {location: String, tz: String};

class Test {
  static function main() {
    var ts: TS;
    if (is_us) {
      ts = {location: "a", tz: "b"};
    } else {
      ts = {location: "a", tz: "b"};
    }
  }
}
enum Tuple {
	Timezone(location:String, tz:String);
}

class Test {
	static function main() {
		var is_us = false;
		var mytz1:Tuple = Tuple.Timezone(
			(is_us) ? 'NEW YORK' : 'PARIS',
			(is_us) ? 'EST' : 'CET'
		);
		var mytz2:Tuple = (is_us) ? Tuple.Timezone('NEW YORK', 'EST') : Tuple.Timezone('PARIS', 'CET');
		switch mytz1 {
			case Timezone(location, tz):
				trace('Location: ${location}, Timezone: ${tz}');
			default:
		}
		switch mytz2 {
			case Timezone(location, tz):
				trace('Location: ${location}, Timezone: ${tz}');
			default:
		}
	}
}

Try Haxe!

1 Like