titzer / virgil

A fast and lightweight native programming language
1.2k stars 42 forks source link

Copy/modify initialization expression - `with`? #135

Open titzer opened 1 year ago

titzer commented 1 year ago
    I am thinking of a construct to make initialization of large, complex structures with named members easier. Some ideas:

with expression

class Config {
  var name: string;
  var size: int;
  var doMore: bool;
  var extraThings: Array<int>;
}

def x = Config.new() with {
  name = "foo";
  size = 44;
  doMore = false;
  extraThings = [88, 99, 1000];
};

The idea of the with expression is that it takes an expression on the left and applies the updates to the fields given in the curlies { ... }. For class types with mutable members, it takes an object, mutates the original object and returns it. For tuples, data types, or ADTs, it would create a new value with the updated fields.

It allows for having lots of parameters via a config object:

class Args { ... }
def m(x: Args) {
  ...
}
var r1 = m(Args.new() with { name = "string"; size = 66; });
// or, eliding the .new():
var r2 = m(Args with {name = "myname"; size = 777; });

Wdyt?

Originally posted by @titzer in https://github.com/titzer/virgil/discussions/122#discussioncomment-4999342