Python-like Use of the Comma Expression

Quirin Schroll qs.il.paperinik at gmail.com
Wed Aug 9 18:30:38 UTC 2023


On Tuesday, 8 August 2023 at 16:47:25 UTC, Vijay Nayar wrote:
> **TL;DR**: The comma operator has little use in D, but perhaps 
> it could be used like in Python, to define tuple expressions.

You can use something like tuple assignment, you can get pretty 
far simulating that with current D’s tools:
```d
struct t
{
     import std.typecons : tuple;
     static opIndex(Ts...)(Ts args) => tuple(args);

     alias opIndexAssign = opIndexOpAssign!"";
     template opIndexOpAssign(string op)
     {
         static void opIndexOpAssign(R, Ts...)(R rhs, ref Ts lhs)
         {
             static foreach (i; 0 .. Ts.length)
             	mixin("lhs[i] ", op,"= rhs[i];");
         }
     }
}

void main()
{
     int x;
     double y;
     t[x, y] = t[2, 3.14];
     assert(x == 2);
     assert(y == 3.14);
     t[x, y] += t[3, 2.71];
     assert(x == 5);
     assert(y == 3.14 + 2.71);
}
```

It doesn’t work with non-copyable values, but it can be made to 
work with some effort (I’ve done that). Other than that, this 
little thing gets you quite far. A rough outline of how to 
support non-copyable types: Make your own tuple-like type to 
store the values that went into and “store” a compile-time bool 
array of whether the values were rvalues or lvalues. When the 
values are read, return originally-lvalue values by reference and 
move the originally-rvalue values (return by value).

Obviously it can’t do declarations and a few other things that 
language-level tuple support would (in all likelihood) bring.


More information about the Digitalmars-d mailing list