On Wednesday, 15 January 2014 at 15:48:13 UTC, John Colvin wrote:
On Wednesday, 15 January 2014 at 15:30:35 UTC, pplantinga wrote:
In python, I really like the ability to check if an element is
in an array:
if x in array:
# do something
D has this, but only for associative arrays. Is there any
chance we could extend this to every kind of array?
import std.algorithm: canFind;
if(array.canFind(x))
//do something
alternatively, something like this:
struct InWrapper(T)
{
T unwrapped;
alias unwrapped this;
auto opBinaryRight(string op, T)(T el)
if(op == "in")
{
import std.algorithm : canFind;
return unwrapped.canFind(el);
}
}
unittest
{
InWrapper!(int[]) arr;
arr = [1,2,3,4];
assert(4 in arr);
assert(!(5 in arr));
}
auto inWrap(T)(T[] arr)
{
static struct InWrapper
{
import std.typecons: Nullable;
private T[] payload;
Nullable!size_t opBinaryRight(string op: "in")(T val)
{
Nullable!size_t index;
foreach (i, element; payload)
{
if (element == val)
{
index = i;
return index;
}
}
return index;
}
}
return InWrapper(arr);
}
void main()
{
auto arr = [0, 1, 2, 3, 4];
auto i = 2 in arr.inWrap;
assert(!i.isNull);
assert(i == 2);
}