Thread overview
Why D have two function contains and canFind?
Jul 24, 2017
Suliman
Jul 24, 2017
Ali Çehreli
Jul 24, 2017
Cym13
Jul 24, 2017
Seb
Jul 24, 2017
Timon Gehr
July 24, 2017
Why D have two function `contains` and `canFind` if C# have only contains and it's enough?


July 24, 2017
On 07/24/2017 11:19 AM, Suliman wrote:
> Why D have two function `contains` and `canFind` if C# have only
> contains and it's enough?

std.algorithm.canFind and std.range.SortedRange.contains:

  https://dlang.org/phobos/std_algorithm_searching.html#.canFind

  https://dlang.org/phobos/std_range.html#.SortedRange.contains

canFind() is more general because it works with any input range. For that reason, it has to walk from the beginning to the end. (O(N) complexity)

contains() requires a sorted random access range so that it can use the O(log N) binary search algorithm.

When you have a large sorted array, use contains(). Even if the array is not sorted but there are many searches to be performed, sorting first and then calling contains() many times may be faster than canFind().

Even if the array is not sorted but it's small, you can use canFind() without worrying about performance. Of course it all depends on what small and large mean. :)

Ali

July 24, 2017
On Monday, 24 July 2017 at 18:31:09 UTC, Ali Çehreli wrote:
> On 07/24/2017 11:19 AM, Suliman wrote:
> > [...]
> only
> > [...]
>
> std.algorithm.canFind and std.range.SortedRange.contains:
>
> [...]

I'm gessing this predates design by introspection as it would be cleaner to let the compiler do the switch itself.
July 24, 2017
On Monday, 24 July 2017 at 19:53:34 UTC, Cym13 wrote:
> On Monday, 24 July 2017 at 18:31:09 UTC, Ali Çehreli wrote:
>> On 07/24/2017 11:19 AM, Suliman wrote:
>> > [...]
>> only
>> > [...]
>>
>> std.algorithm.canFind and std.range.SortedRange.contains:
>>
>> [...]
>
> I'm gessing this predates design by introspection as it would be cleaner to let the compiler do the switch itself.


Yes - since end of 2016 `find` (and thus `canFind`) do introspection:

https://github.com/dlang/phobos/pull/4907
https://github.com/dlang/phobos/blob/57b8d2511ea37cd01665b9b663d8ba246144b1f9/std/algorithm/searching.d#L1509

Thus, I believe it would be best to deprecate SortedRange.contains:

https://github.com/dlang/phobos/pull/5651
July 25, 2017
On 24.07.2017 20:19, Suliman wrote:
> Why D have two function `contains` and `canFind`

`contains` guarantees logarithmic running time, while `canFind` can be linear.