Towards better integration of struct/tuple/array

Dmitry Olshansky dmitry.olsh at gmail.com
Wed May 23 04:00:06 PDT 2012


> My proposal the is following using a.{ ... } syntax to unpack:

In short:
I think the original proposal of
  https://github.com/D-Programming-Language/dmd/pull/341
could be enhanced with introduction  <expr>.{ <spec> } selectors 
allowing to cherry pick fields and array elements easily.

If we go with Kenji's proposal, this can be treated as cool way to 
construct tuple by applying selector to an expression.

>
> Record r = ...;
> auto a, b, c = r.{ first, third, some_other_field };//a=r.first,
> b=r.third, c = r.some_other_field
>
> With tuples:
> auto a, b, c = r.{};//a = r[0], b = r[1], c = r[2]
> auto a, b, c = r.{0, 2, 4}; // a = r[0], b = r[2], c = r[4]
>
> With arrays, exactly the same as tuples:
> auto a, b, c = r.{0, 2, 4}; // a = r[0], b = r[2], c = r[4]
>
> Tuples with named fields can work in both named and indexed "modes".
> Indexes must be a valid CT-constant.
>
> More over we then have nested unpacking syntax:
>
> auto x, i = r.{ something, nested_thing.{ precious_secret} };
> //x = r.something, i = r.nested_thing.precious_secret
>
> The same with just about any expression:
>
> auto point = (a+b()).{ x, y };
> //even better - point is now Tuple!(<type of x>, "x", <type of y>, "y")
>
>
> Summarizing it all.
>
> For single left-side variable the rewrite of expression is:
> auto __tmp = <expr>, tuple(__tmp.<spec_1>, __tmp.<spec_2>);
>
> For multiple left-side the rewrite of the whole statement is:
> auto __tmp = <expr>, __1st = __tmp.<spec_1>, __2nd = __tmp.<spec_2> ...;
>
>
> Where spec_x is constructed from:
>
> root_0.{ ... root_1.{ .. root_n.{ var_x ... } ... } ... }
>
> as
> root_0.<...>.root_n.var_x
>
> If some var_k/root_k happens to be CT index the rewrite is
> ...[root_k]... or ...[var_k]..
>
>
> So far I think it's the closest thing to multiple value return with
> natural syntax. It also brings concise syntax for a common general
> propose task.
>




-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list