Completing C code with D style

jfondren julian.fondren at gmail.com
Thu Nov 4 00:53:11 UTC 2021


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:

```d
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;
     auto numbers = [-3, 14, 47, -49, -30, 15, 4, -82, 99, 26];
     alias match = (ns, s, p) => ns.equal(numbers.filter!(n => 
simple(n, s, p)));

     assert(match(numbers, sign.both, parity.both));
     assert(match([-3, -49], sign.negatives, parity.odds));
     assert(match([-30, -82], sign.negatives, parity.evens));
     assert(match([14, 4, 26], sign.positives, parity.evens));
     assert(match([47, 15, 99], sign.positives, parity.odds));
     assert(match([-3, -49, -30, -82], sign.negatives, 
parity.both));
     assert(match([14, -30, 4, -82, 26], sign.both, parity.evens));
}
```


More information about the Digitalmars-d-learn mailing list