D with experimental features like tuple unpacking

Dmitry Olshansky dmitry.olsh at gmail.com
Fri Mar 22 05:13:40 PDT 2013


22-Mar-2013 15:25, bearophile пишет:
> Dmitry Olshansky:
>
>>> auto (lof, loa) = ...;
>>>
>>> In Haskell, Scala, Python, F#, etc, the semantics and syntax are
>>> similar.
>>>
>>
>> I'd hate any solution that distances ordinary structs, library tuples
>> and fixed-sized arrays. If anything these should be trivially
>> substitutable where makes sense.
>
> In Bugzilla I suggested that syntax for arrays too, I'd like that:
>
> int[2] data = [10, 20];
> auto (a, b) = data;
>
>
> Regarding tuples and structs, Tuples are implemented as structs, so
> forbidding struct unpacking is probably more work than not doing it. On
> the other hand structs and tuples are not exactly the same thing,
> despite one is implemented with the other.

What the heck this paragraph supposed to mean? Sorry I can't get the 
message out of it.

What I think is that unpacking both tuples, structs and _fixed_ arrays 
has to be done the same way, period. That way has to be easy, concise 
and non error prone. Otherwise I'd call it all a failure.

Dynamic arrays are the different beasts we may postpone decision on 
whether unpacking these in the same vein makes sense.

>
>> I even had proposal to about same effect, but it was ignored. Among
>> other things it replace .tupleof with more general destructuring
>> facility.
>
> I don't want to use ".tupleof" to unpack a Tuple. Because it's a very
> commonly done operation, so it needs a short syntax.
>

What I've meant is to add easily controllable way to slice up fields 
from structs as tuples (pretty much as .tupleof is doing but more 
fine-grained) see:

struct P { int x; int y; double d; }

P p = P(2, 5, 5.6);

auto (x,y) = p.{x, y};  // + your unpacking

p.{x,y} = p.{y,x}; // anmd many more short-hand things are possible

Nested stuff is also no problem:

struct J{ P a; P b; double r; }

J j = ....;

auto (first, second, last) = j.{a, b.{y}, r};
static assert(typeof(first) == P);
static assert(typeof(second) == int);
static assert(typeof(last) == double);

Same with any nesting depth, b.{x,y} has type (int,int) as internal 
tuple or Tuple!(int, int) as in Phobos but it'd better be in druntime then.

.tupleof is then done as trivial default:

auto unpacked = j.{};
static assert(typeof(unpacked) == Tuple!(P, P, double));


-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list