How about a function called contains() for the module std.array?

Murilo murilomiranda92 at hotmail.com
Sun Oct 20 02:58:15 UTC 2019


On Sunday, 20 October 2019 at 02:46:24 UTC, Les De Ridder wrote:
> On Saturday, 19 October 2019 at 21:47:57 UTC, Murilo wrote:
>> I needed a function that tells if an array contains the 
>> elements of another, as in `[1, 2, 3, 4, 5, 6].contains([6, 
>> 4])` by returning a `bool`. I did not find such function so I 
>> made my own version but I'm unable to submit a PR on GitHub 
>> since I don't know how to write a function using that style 
>> that I saw on GitHub. I imagine that maybe you guys could take 
>> my function and refactor it so it will be according to your 
>> rules and then add it to std.array. What do you think?
>> Here is my function:
>> //This function returns a bool telling if an array totally 
>> contains the elements of a smaller array
>> import std.algorithm.searching : countUntil;
>> import std.algorithm.sorting : sort;
>>
>> bool contains(long[] a, long[] b)
>> {
>>     //first we sort both of them
>>     sort(a);
>>     sort(b);
>>     //now we check them using slices and return the result
>>     return b == a[a.countUntil(b[0]) .. a.countUntil(b[$ - 1]) 
>> + 1];
>> }
>> /*
>> Example:
>> long[] a = [3, 9, 1, 4, 7, 6, 5, 8, 2];
>> long[] b = [5, 4, 6];
>> writeln(contains(a, b));
>> */
>
> You could do something like this:
>
>     import std.stdio;
>     import std.algorithm : all, canFind;
>
>     auto a = [1, 2, 3, 4, 5, 6];
>     auto f = [3, 5, 6].all!(n => a.canFind(n));
>     writeln(f);
>
> PS: this should probably have been posted to the Learn list.

That worked, thanks! But I find that too complicated, just a 
function would be easier.


More information about the Digitalmars-d mailing list