how to assign multiple variables at once by unpacking array?
Salih Dincer
salihdb at hotmail.com
Mon Oct 9 01:15:21 UTC 2023
On Saturday, 7 October 2023 at 16:12:47 UTC, mw wrote:
> Interesting: in terms of easy of coding, clarity and future
> maintenance, which one is superior?
>
> The one liner in Python, or your "solution" with dozen lines of
> code? BTW, is that a solution at all? Did it achieved what the
> original goal asked in the OP question?
>
> So, who should learn from whom?
If you don't expect to do a single line of coding, there are many
methods in D that can do this kind of thing (but at compile time).
**Your snippet with struct and tupple:**
```d
import std;
struct MyVariables
{
int age, phone, country;
}
void main()
{
enum sep = ", ";
enum str = "21, 3149474, 90";
enum arr = str.split(sep)
.map!(x => x.to!int)
.array//*/
;
alias MrSmith = AliasSeq!(arr[0],
arr[1],
arr[2]);
auto mv = MyVariables(MrSmith);
assert(mv == MyVariables(21, 3149474, 90));
}
```
and **worksheet example:**
```d
import std;
struct DATA(string str, T, size_t s)
{
enum title = str;
T[s] data;
}
void main()
{
alias Columns = AliasSeq!("Stock Name", "PN Codes", "P.Prices");
alias T = AliasSeq!(string, int, double);
alias Items = AliasSeq!(4, 8, 8);
staticMapN!(3, DATA, Columns, T, Items) worksheet;
// inputs first column:
worksheet[0].data = ["capacitor", "transistor", "resistor",
"varistor"];
// prints column titles:
foreach(s; worksheet)
s.title.writef!"%14s";
"=".repeat(42).writefln!"\n%-(%s%)";
// prints first column:
foreach(name; worksheet[0].data)
name.writefln!"%14s";
//...
"=".repeat(42).writefln!"%-(%s%)";
}/* Prints:
Stock Name PN Codes P.Prices
==========================================
capacitor
transistor
resistor
varistor
==========================================
*/
```
By the way, in order for the above code snippet to work, the
staticMapN() template implemented by Ali Çehreli, which is not in
the standard library, is needed:
```d
template staticMapN(size_t N, alias fun, args...)
if(args.length % N == 0)
{
alias staticMapN = AliasSeq!();
static foreach (i; 0..args.length / N)
{
static if (N == 1)
{
staticMapN = AliasSeq!(staticMapN, fun!(
args[i]
));}
else static if (N == 2)
{
staticMapN = AliasSeq!(staticMapN, fun!(
args[0..$ / N][i],
args[$ / N..($ / N) * 2][i]
));}
else static if (N == 3)
{
staticMapN = AliasSeq!(staticMapN, fun!(
args[0..$ / N][i],
args[$ / N..($ / N) * 2][i],
args[($ / N) * 2..($ / N) * 3][i]
));}
}
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list