May 03

On Friday, 3 May 2024 at 15:19:13 UTC, user1234 wrote:

>

On Friday, 3 May 2024 at 14:59:57 UTC, BoQsc wrote:

>

On Friday, 3 May 2024 at 13:18:02 UTC, user1234 wrote:

>

[...]

So how would you update this example, what is the right index type here to choose?

import std.stdio : writefln;

void main() {
    auto arr = [
        [5, 15],      // 20
        [2, 3, 2, 3], // 10
        [3, 6, 2, 9], // 20
    ];

    foreach (i, row; arr)
    {
        double total = 0.0;
        foreach (e; row)
            total += e;

        auto avg = total / row.length;
        writefln("AVG [row=%d]: %.2f", i, avg);
    }
}

Example taken from https://tour.dlang.org/tour/en/basics/foreach

Isn't that obvious ?

foreach (const size_t i, row; arr)

arr is not a static array, it is a dynamic one, consequently its .length type is size_t, even if you have the feeling that, in the present situation, int bitwidth would be sufficient.

even better:

foreach (const typeof(arr.length) i, row; arr)

Otherwise I respect your POV, it's just that here I have no problem with the way that works. I dont see any issue with the type system. D type system is static, strong, but optionally inferred. And that's it.

May 04

Well all these proposals to int index like size_t and const typeof(arr.length) are cryptic and less readable and less straightforward in comparison to how it used to be. Feels like horrible decision if the language is suppose to be somewhat futureproof. The int was simple, straighforward and great. These suggestions feel like some C++ all over again.

May 12

A horrible alternative would be to use alias on size_t to make up a new pseudo-type that is more aligned with the code logic.

alias integer = size_t;
import std.stdio : writefln;

void main() {
    auto arr = [
        [5, 15],      // 20
        [2, 3, 2, 3], // 10
        [3, 6, 2, 9], // 20
    ];

    foreach (integer i, row; arr)
    {
        double total = 0.0;
        foreach (e; row)
            total += e;

        auto avg = total / row.length;
        writefln("AVG [row=%d]: %.2f", i, avg);
    }
}
1 2
Next ›   Last »