let (x,y) = ...

Mengu via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Thu Feb 19 03:03:56 PST 2015


On Thursday, 19 February 2015 at 04:38:32 UTC, thedeemon wrote:
> Creating tuples and returning them from functions is trivial in 
> D:
>
> auto getTuple() { return tuple("Bob", 42); }
>
> but using them afterwards can be confusing and error prone
>
> auto t = getTuple();
> writeln("name is ", t[0], " age is ", t[1]);
>
> I really missed the ML syntax to write
>
> let (name, age) = getTuple();
>
> Turns out this is ridiculously easy to implement in D, so 
> here's my very tiny module for this:
>
> https://bitbucket.org/infognition/dstuff/src (scroll down to 
> letassign.d)
>
> It allows you to write:
>
> int x, y, z, age;
> string name;
>
> let (name, age) = getTuple();           // tuple
> let (x,y,z) = argv[1..4].map!(to!int);  // lazy range
> let (x,y,z) = [1,2,3];                  // array
>
> SomeStruct s;
> let (s.a, s.b) = tuple(3, "piggies");
>
> If a range or array doesn't have enough elements, this thing 
> will throw, and if it's not desired there's
> let (x,y,z)[] = ...
> variant that uses just the available data and keeps the rest 
> variables unchanged.

that's a great example to show d's strength. thank you.


More information about the Digitalmars-d-announce mailing list