Why 'in' works only for assoc arrays?

IchorDev zxinsworld at gmail.com
Sat Dec 28 12:13:36 UTC 2024


On Friday, 27 December 2024 at 19:17:13 UTC, JN wrote:
> ```d
> int[] numbers;
> if (3 in numbers) // doesn't work, compiler recommends 
> std.algorithm.find
>
> string buildLog;
> if ("build error" in buildLog) // doesn't work, compiler 
> recommends std.algorithm.find
> ```
>
> Good thing that compiler recommends what to use instead, but 
> why not just make it work for any container?

Because looking up a key in an associative array is defined by 
its implementation. Associative arrays come with a lot of 
baggage, whereas slices (AKA dynamic arrays) really do not. 
Additionally, slices couldn't provide a succinct implementation 
for 'finding an item' or 'finding series of items' because there 
are various implementation-details for a search algorithm that 
the programmer (not the compiler) needs to decide, including:
- How are you checking for equality? (e.g. is `-0f in [0f]` true 
or false?)
- What kind of search are we using? Linear, Boyer-Moore, etc.?
- Can we assume the array sorted?

`std.algorithm.searching` intelligently accounts for many of the 
various problems with having a one-size-fits-all 'search' 
function.
For example, if you want `-0f in [0f]` to be true:
```d
[0f].canFind!"a == b"(-0f);
```
And if you want it to be false:
```d
[0f].canFind!"a is b"(-0f);
```
You can get a lot out of such a versatile function, even making 
it do things it wasn't strictly intended to do:
```d
[1f, 10f, 20f].canFind!"a > b"(10f); //checks if any of the items 
are greater than 10
```
You wouldn't be able to get the same flexibility out of `in`. It 
would either be too implementation-defined (i.e. unreliable); or 
too specific, thereby necessitating that you use `canFind` most 
of the time anyway for its superior expressive power.


More information about the Digitalmars-d-learn mailing list