let (x,y) = ...

thedeemon via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Wed Feb 18 20:38:31 PST 2015


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.


More information about the Digitalmars-d-announce mailing list