Completing C code with D style
kdevel
kdevel at vogtner.de
Sat Nov 6 13:27:55 UTC 2021
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)? 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 ];
```
If 0 is included in the domain the classification of the values
into negative and positive ones is not complete since 0 is
neither.
```
enum sign { negatives = 'n', positives = 'p', both = 'b' }
enum parity { evens = 'e', odds = 'o', both = 'b' }
bool simple(int n, sign s, parity p) {
if (n < 0 && s == sign.positives) return false;
if (n > 0 && s == sign.negatives) return false;
if (n & 1) {
if (p == parity.evens) return false;
} else {
if (p == parity.odds) return false;
}
return true;
}
unittest {
import std.algorithm : filter, equal;
version (have_zero) {
auto numbers = [-2, -1, 0, 1, 2];
}
else {
auto numbers = [-2, -1, 1, 2];
}
alias match = (ns, s, p) => ns.equal(numbers.filter!(n =>
simple(n, s, p)));
assert(match(numbers, sign.both, parity.both));
assert(match([-1], sign.negatives, parity.odds));
assert(match([-2], sign.negatives, parity.evens)); // fails
when we have_zero
assert(match([2], sign.positives, parity.evens));
assert(match([1], sign.positives, parity.odds));
assert(match([-2, -1], sign.negatives, parity.both));
assert(match([-2, 2], sign.both, parity.evens));
}
```
```shell
$ dmd -version=have_zero -checkaction=context -unittest -main
-run a.d
a.d(27): [unittest] false != true
1/1 modules FAILED unittests
```
More information about the Digitalmars-d-learn
mailing list