On Saturday, 6 November 2021 at 13:27:55 UTC, kdevel wrote:
On Thursday, 4 November 2021 at 00:53:11 UTC, jfondren wrote:
On Wednesday, 3 November 2021 at 20:36:08 UTC, russhy wrote:
Keeping things simple helps debugging!

I'd still have to run your program to be sure of its simple logic, though. The real star d feature that would help with debugging is unittest:

What about the number 0 (zero)?

Not treating it as positive is a bug that I introduced in a rewrite.

If 0 is considered to be excluded from the domain how would one define in D a type which cannot represent 0 in the first place? Follow-up question: Are there language facilities such that one could initialize an array of these non-zero-ints like?:

```
   nzint [] numbers = [ -2, -1, 1, 2 ];
```

In general, you use a constructor that tests for non-zero and you take care to maintain the invariant. D has some tools (like invariant) to help with that, but it's not a dependent-typed language.

For this specific example, you can sort of do that with std.typecons.Nullable

```d
unittest {
    import std.typecons : Nullable, nullable;
    import std.algorithm : map;
    import std.array : array;

    alias NonZero(T) = Nullable!(T, 0);

NonZero!int[] numbers = [-2, -1, 0, 1, 2].map!(i => NonZero!int(i)).array;

    int sum;
    int invalids;
    foreach (n; numbers) {
        if (n.isNull) invalids++;
        else sum += n.get;
    }
    assert(sum == 0);
    assert(invalids == 1);
}
```

Reply via email to