how to assign multiple variables at once by unpacking array?

Salih Dincer salihdb at hotmail.com
Sat Oct 7 12:01:07 UTC 2023


On Saturday, 7 October 2023 at 07:31:45 UTC, mw wrote:
> https://stackoverflow.com/questions/47046850/is-there-any-way-to-assign-multiple-variable-at-once-with-dlang
>
> How to do this Python code in D:
>
> ```
>>>> s = "1 2 3"
>>>> A,B,C = map(int, s.split(" "))
>>>> A,B,C
> (1, 2, 3)
>
> ```
>
> Is there a better way (since 2017)?

My words to those who come from Python:

If you are making money from Python, please stay there, but if 
you want to learn new things and a modern language, "Welcome to D"

and please use Tuples :)

```d
import std.typecons, std.stdio;

struct DICT(C, F, S)
{
   S[C] dict;
   C[F] freq;

   void opAssign(Tuple!(C, F, S) chr) {
     dict[chr[0]] = chr[2];
     freq[chr[1]] = chr[0];
   }

   string toString() const
   {
     import std.array : appender;
     import std.algorithm : sort;
     import std.format : formattedWrite;

     auto r = appender!string;
     foreach(f; freq.keys.sort!"a>b") {
       auto key = freq[f];
       r.formattedWrite("(%c) %s, %.1f\n",
                     key, dict[key], f);
     }
     return r.data;
   }
}

void main()
{
   alias index = char;
   alias rank = float;
   alias name = string;

   alias Dict = DICT!(index, rank, name);
   alias chr = Tuple!(index, rank, name);

   auto chrs = [ chr(44, 61.3, "Comma"),
                 chr(34, 26.7, "Doublequote"),
                 chr(39, 24.3, "Apostrophe"),
                 chr(45, 15.3, "Hyphen"),
                 chr(63,  5.6, "Question"),
                 chr(58,  3.4, "Colon"),
                 chr(33,  3.3, "Exclamation"),
                 chr(59,  3.2, "Semicolon")
   ];

   Dict enDict;
   foreach(tup; chrs) //multiple insertion
     enDict = tup;

   writeln("Frequency distributions of punctuation marks used in 
English: ");
   enDict = chr(46, 65.3, "Dot"); // single insertion
   enDict.writeln;
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list