The operator in
between T
and T[]
is requested a lot of times. Most people suggest it should return a bool
signifying if some value of the array on the right-hand side is equal (==
) to the T
value on the left-hand side. This is the obvious thing to do.
I guess it has never been implemented because this information (true/false) is so much less than it could be. If D used 1-based indexing, in
could return the index if found or 0 if not found. Because 0 == false, one could use if (auto x in array)
. However, D's indexing 0-based, so 0 is a valid index. in
cannot return a plain size_t
.
My idea is inspired by how AAs in
operator does not return a (near-useless) bool
, but a value that can be used like a bool
, but provides much more valuable information: a T*
. It would work returning a T*
for slices' in
as well, but it is much less useful than the index. (One could get the index of something from the pointer to it using pointer subtraction, but pointer arithmetic not considered @safe
.) The index practically is the pointer.
So, can we return an object that is, for almost all intents and purposes, usable as an index, but evaluating it via if
returns true
or false
depending on whether the value was found or not.
So, my suggestion is that the in
operator for slices returns a value of this type:
struct InResult
{
size_t index = size_t.max;
alias index this;
bool opCast(T : bool)() const { return index != size_t.max; }
}
In fact, this is very much a simple optional type. It takes a very unlikely valid value of its underlying type and reinterprets it as the invalid value.