www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - [Sharing]Tuple to variables (My Function)

reply "MattCoder" <mattcoder hotmail.com> writes:
Hi,

Sooner I asked about this ([Doubt] Variadic arguments as 
reference (Possible?) - - 
http://forum.dlang.org/thread/jwujjhjizkovvmbegaio forum.dlang.org).

In fact my intend was to recreate a feature that I like in 
Python, where you can assign variables from a tuple, e.g.:

pos = (10, 20)
x,y = Pos

or

RGB = (255,255,255)
r,g,b = RGB

Thanks to the fellows who help me early morning, I wrote the 
workable version below:

import std.stdio;
import std.typecons;
import std.variant;

void tupleToVar(A, T...)(A inTuple, ref T listParams){
   foreach(i, ref p; listParams){
     if(!(i<inTuple.length))
       break;

     p = inTuple[i];
   }
}

void main()
{
     auto myTuple = tuple(1,2,3,"Test");
     Variant a, b, c, d;
     tupleToVar(myTuple, a, b, c, d);
     writeln(a);
     writeln(b);
     writeln(c);
     writeln(d);
}

dpaste: http://dpaste.dzfl.pl/6f3f25d0

It would be nice if it could appear more like python, but I think 
this would be a internal dev.

Matheus.
Jun 14 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
MattCoder:

 void tupleToVar(A, T...)(A inTuple, ref T listParams){
I think in the C++11 STL a similar function is named tie.
     if(!(i<inTuple.length))
       break;
You have to verify in the function constraint that the lengths match.
 It would be nice if it could appear more like python, but I 
 think this would be a internal dev.
There is a DIP about it, but it's currently stalled: http://wiki.dlang.org/DIP32 Bye, bearophile
Jun 14 2013
parent "MattCoder" <mattcoder hotmail.com> writes:
On Saturday, 15 June 2013 at 00:47:01 UTC, bearophile wrote:
 You have to verify in the function constraint that the lengths 
 match.
In fact that was intentional, because sometimes I just want few items from a tuple not all. For example: auto RGB = tuple(255, 125, 50); Variant r,g; tupleToVar(RGB, r, g); // I just want the red and green values from a tuple Matheus.
Jun 14 2013