Is a shorter statement possible in this case?

Paul Backus snarwin at gmail.com
Mon Nov 6 13:06:07 UTC 2023


On Sunday, 5 November 2023 at 18:36:40 UTC, Ctn-Dev wrote:
> I wrote this earlier:
>
> [...]
>
> `if` runs when both "One" and "Two" are in the given array as 
> intended, but its conditional statement looks verbose. Is there 
> a more concise way of getting the same result?

If sorting the arrays is an option, you can use `setIntersection` 
from `std.algorithm.setops`, which returns the overlap between 
two sorted ranges:

```d
import std.stdio;
import std.algorithm.searching: count;
import std.algorithm.setops: setIntersection;
import std.algorithm.sorting: sort;

string[] numeric_traits_1 = [];
string[] numeric_traits_2 = ["Two"];
string[] numeric_traits_3 = ["One"];
string[] numeric_traits_4 = ["One", "Two"];

void main() {

     void numeric_traits_contains(string[] numeric) {
         sort(numeric); // required by setIntersection
         size_t howMany = setIntersection(numeric, ["One", 
"Two"]).count;
         if (howMany == 2) {
             writeln("Array contains 'One' and 'Two'.");
         } else if(howMany == 1) {
             writeln("Array contains 'One' or 'Two'.");
         } else {
             writeln("Array contains neither 'One' nor 'Two'");
         }
     }

     numeric_traits_contains(numeric_traits_1);
     numeric_traits_contains(numeric_traits_2);
     numeric_traits_contains(numeric_traits_3);
     numeric_traits_contains(numeric_traits_4);
}
```


More information about the Digitalmars-d-learn mailing list