std.algorithm.canFind behavior difference between arrays and elements

Steven Schveighoffer schveiguy at gmail.com
Fri Dec 7 20:18:12 UTC 2018


On 12/7/18 2:38 PM, Arun Chandrasekaran wrote:
> On Friday, 7 December 2018 at 19:12:31 UTC, Seb wrote:
>> On Friday, 7 December 2018 at 18:51:27 UTC, Arun Chandrasekaran wrote:
>>> I'm trying to find the needle in the hay that's an array of strings. 
>>> So the second assert fails for some reason. Is this expected? 
>>> https://run.dlang.io/is/7OrZTA
>>>
>>> ```
>>> #!/usr/bin/rdmd
>>>
>>> void main()
>>> {
>>>     import std.experimental.all;
>>>     string s1 = "aaa111aaa";
>>>     string s2 = "aaa222aaa";
>>>     string s3 = "aaa333aaa";
>>>     string s4 = "aaa444aaa";
>>>     const hay = [s1, s2, s3, s4];
>>>     assert(canFind(s1, "111"));
>>>     assert(canFind(hay, "111"));
>>> }
>>> ```
>>>
>>> Why is there a difference in the behavior?
>>
>> Alternatively to the answers above you can also use a custom lambda 
>> for canFind:
>>
>> https://run.dlang.io/is/QOXYbe
> 
> Just curious, how do we find multiple needles? This throws compilation 
> error
> 
>      assert(hay.canFind!(e => (e.canFind(["111", "222"]))));

Almost, you have extra braces:

        assert(hay.canFind!(e => (e.canFind( "111", "222" ))));

In other words, when searching for extra needles, each needle is a new 
parameter to find/canFind.

-Steve


More information about the Digitalmars-d-learn mailing list