www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why D have two function contains and canFind?

reply Suliman <evermind live.ru> writes:
Why D have two function `contains` and `canFind` if C# have only 
contains and it's enough?
Jul 24
next sibling parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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
Jul 24
parent reply Cym13 <cpicard openmailbox.org> writes:
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.
Jul 24
parent Seb <seb wilzba.ch> writes:
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
Jul 24
prev sibling parent Timon Gehr <timon.gehr gmx.ch> writes:
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.
Jul 24