how to assign multiple variables at once by unpacking array?
Martyn
martyn.developer at googlemail.com
Wed Oct 11 12:12:41 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:
> ...
> ...
> Is there a better way (since 2017)?
Each programming language has their pros and cons. They all have
their way of solving the problem. A higher level language,
generally, allows you to write less code compared to a lower
level one.
ie - A Python program thats 20 LOC could be 50 LOC in C99 or much
much more.
The downside to (something like) python is that writing less code
has its drawbacks. What does it do in background? Can there be a
huge performance penalty once inside a loop?
D provides you the power of being low level like C, or high level
that can be comparable in a number of ways to C#. I have a choice
to turn off the GC, if I want to!
My response to this is, without sounding rude, who cares about
your example?
- Could D be able to achieve this? Maybe.
- If not, could it in the future? Maybe.
- Would you still have to write an extra line or two compared to
the Python example? Maybe.
You are just splitting a string to 3 variables as ints.
>
> ```
>>>> s = "1 2 3"
>>>> A,B,C = map(int, s.split(" "))
>>>> A,B,C
> (1, 2, 3)
>
> ```
"What if" s has more than 3 numbers?
"What if" s includes characters?
Python will spit out an error - "not enough values" or "invalid
literal"
To build reliable code in your example add more LOC.
I can do this in D. May not be the best example. Is stores them
in int arrays and
handles potentials characters:-
```d
void main()
{
import std.stdio;
import std.array;
import std.string;
import std.algorithm;
import std.conv;
auto s = "1 2 a 3";
auto abc = s.split(' ').map!(s => isNumeric(s) ? s.to!int :
-1);
writeln(abc); // [1, 2, -1, 3]
}
```
I will leave it there.
More information about the Digitalmars-d-learn
mailing list