More uses of operator "in"

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 28 11:38:18 PDT 2014


On Tuesday, 28 October 2014 at 18:29:49 UTC, Marc Schütz wrote:
> On Tuesday, 28 October 2014 at 17:50:30 UTC, Baz wrote:
>> On Tuesday, 28 October 2014 at 16:32:13 UTC, Marc Schütz wrote:
>>> On Tuesday, 28 October 2014 at 15:11:01 UTC, Baz wrote:
>>>> On Tuesday, 28 October 2014 at 13:50:24 UTC, Nordlöw wrote:
>>>>> Has there been any proposals/plans to make operator "in" 
>>>>> work for elements in ranges such as
>>>>>
>>>>> assert('x' in ['x']);
>>>>>
>>>>> I'm missing that Python feature when I work in D.
>>>>
>>>> There is also something similar in Pascal, at the language 
>>>> level. Very handy when working with characters or enums.
>>>
>>> AFAIR it's limited to sets in Pascal, where its complexity is 
>>> O(1).
>>
>> If "in" is used as a syntactic sugar, e.g to call 
>> "std.algorithm.canFind" in a custom type, then why would the 
>> bigO be a concern ?
>
> It always was the argument against generalizing `in` to arrays. 
> `in` is not alone in this respect. It's also expected that 
> indexing and slicing be "cheap" operations.

To answer your question: Computational (or memory) complexity is 
not an implementation detail, because it has a very noticeable 
effect. Therefore, one should not hide an O(n) or worse operation 
behind a harmless looking expression. It's not a technical 
requirement, of course, but a convention that makes a lot of 
sense IMO.

D is relatively consistent in this respect. Not only does it 
apply to `in` and the aforementioned indexing and slicing, but 
there's also the convention that ranges shouldn't provide 
operations they cannot implement cheaply. For example, a 
singly-linked list shouldn't provide `back` and `popBack()` 
primitives, because while it is possible to implement them, they 
would be expensive, which could surprise an unsuspecting user.


More information about the Digitalmars-d-learn mailing list