Suggestion: Operator `in` for slices

Paul Backus snarwin at gmail.com
Mon Dec 20 14:21:08 UTC 2021


On Monday, 20 December 2021 at 13:54:56 UTC, Ola Fosheim Grøstad 
wrote:
> On Monday, 20 December 2021 at 11:04:00 UTC, Dennis wrote:
>> On Sunday, 19 December 2021 at 18:31:46 UTC, Steven 
>> Schveighoffer wrote:
>>> There's your answer -- make a custom type that allows `in` 
>>> with an array-like structure.
>>
>> For the record, I'm not arguing in favor of `in` for slices. 
>> I'm just baffled that whenever this comes up, the first thing 
>> people bring up is the 'time complexity' argument.
>
> Yes, I agree with this. When I use "in" in Python I am very 
> much aware that it does a linear scan, but it is a very useful 
> shorthand that can replaces a long and confusing sequence of 
> or-expressions.
>
> E.g.
>
> ```
> if keyword in ['if', 'while', 'for]
> ```
>
> is a very useful and clear syntactical construct.

```d
import std.algorithm.searching;

if (["if", "while", "for"].canFind(keyword)) {
     // ...
}
```


More information about the Digitalmars-d mailing list