variable destructuring in D (tuples and ranges)

Timothee Cour thelastmammoth at gmail.com
Tue Feb 20 19:20:37 UTC 2018


see https://forum.dlang.org/post/p3bdp1$2b4e$1@digitalmars.com [Tuple DIP]

On Tue, Feb 20, 2018 at 11:01 AM, valmat via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
> Hi there!
> I just started learn D.
> First it is greatful language.
> But unfortunatly it doesn't have variable destructuring syntax.
> Like this:
> ```
> auto x,y,z = tuple(26, "hi", 'a');
> auto x,y,z = [1,2,3];
> auto x,y,z = anyRange;
> ```
> Because it is convenient i wrote my own implementation of this opportunity
>
> Here is an example:
> ```
> import std.stdio    : writeln;
> import std.typecons : tuple;
> import vlm.utils.destructing : tie;
>
> void main()
> {
>     // Traversable (arrays or any lazy ranges)
>     string a, b, c;
>     tie(a,b,c) = ["foo1","foo2","foo3","foo4","foo5","foo6"];
>     // May retrive undercomplit ranges
>     tie(a,b,c) = ["bar1","bar2"];
>
>     size_t i, j, k;
>     float pi;
>     int l;
>     // Automatically cast types (int -> size_t)
>     tie(i,j,k) = [1,2];
>     tie(i,pi,l) = [3.14, 3.14, 3.14];
>
>     // Tuples
>     int    x;
>     string y;
>     char   z;
>     size_t u,v,w;
>
>     tie(x,y,z) = tuple(1, "hello", 'a', 777, 3.14);
>     tie(x,y,z) = tuple(15, "world");
> }
> ```
>
> The sourse code is here:
> https://gist.github.com/valmat/763c72465d7a1737229ae1c91393d629
>
> I would be glad if this would be useful for you
>
> And how about to consider of inclusion this possibility in the language?
>
> PS
> i'm newbie in D so may be my code is not optimal.
> I'm used to writing in C++ style and maybe in D part of my code could be
> easier


More information about the Digitalmars-d mailing list