tuple-syntax

electricface electricface at qq.com
Tue Mar 19 05:43:25 UTC 2024


On Sunday, 17 March 2024 at 20:20:52 UTC, Dom DiSc wrote:
> I just viewed the D-Conf online talk about new syntax for 
> tuples and had an idea I need to suggest:
>
> One of the proposals was to use normal round brackets. But this 
> would required to use something special to distinguish 
> one-element tuples from from a parenthesized expression. It 
> suggested a trailing comma for this case. But it has the second 
> flaw that it remains unclear how to express an empty tuple 
> unambiguously.
>
> So, how about _always_ requiring a trailing comma?
> This would make for a consistent syntax: (,) empty tuple, (x,) 
> one-element tuple, (x,y,) two element tuple ...
>
> Just an idea.

I have also reviewed the documentation for the tuple speech. 
Below is the tuple syntax that I have designed, which I believe 
is more structured and easier to distinguish:

tuple type syntax

EOT in tuple "()" as a keyword.

```
// tuple type and tuple literal
(-) t0 = (EOT)
(int-) t1 = (1, EOT)
(int-int) t2 = (1,2)
(int-int-string) t2 = (1,2,"ABC")

// unpack
auto (EOT) = (EOT);
auto (a, EOT) = (1, EOT) // a = 1
auto (a, b) = (1, 2) // a = 1, b = 2
auto (x, (y, z)) = (1, (2, 3)) // x = 1, y = 2, z = 3
auto (x, y, (z, EOT), (EOT)) = (1,2, (3, EOT), (EOT)) // x = 1, y 
= 2, z = 3


auto t = (1, EOT)
// to string
writeln(t) // (1)
// unpack
auto (x , EOT) = t // x = 1

auto t2 = (1, 2)
// unpack with type
(int64 v1, auto v2) = t2 // v1 = 1, v2 = 2

// function define
int foo(int a, int b) => a + b;

int func0( (-) t ) => 0;

int func1( (int-) t ) => t[0];
// with unpack
int func1_u( (int-)(v1, EOT) ) => v1;

int func2( (int-int) t ) => t[0] + t[1];

// with unpack
int func2_u( (int-int)(v1, v2)   ) => v1 + v2;

// call function
foo( 1,2 ) // ok
foo( (1,2).expand )  // ok
foo( (1,2) ) // error

func0( (EOT) ) // ok
func0() // err

func1( (1,EOT) ) // ok
func1( 1 ) // err

func1_u( (1,EOT)) // ok
func1_u( 1 ) // err

func2( (1,2) ) // ok
func2( 1, 2 ) // err

func2_u( (1, 2)) // ok
```


More information about the Digitalmars-d mailing list