Is there any reason why in can't work with dynamic arrays?

Adam D. Ruppe destructionator at
Wed Sep 18 01:27:09 UTC 2019

On Tuesday, 17 September 2019 at 18:10:40 UTC, Brett wrote:
> Alternatively, have a keys for a DA:
> then one can do
> if (y in x.keys)


Actually, fun fact: you can do that in your own code. Write a 
function `keys` that returns a struct implementing 

Like so:

import std.stdio;

struct KeyRange {
	size_t max;
	bool opBinaryRight(string op : "in")(size_t v) {
		return v >= 0 && v < max; // the < 0 never passes but meh 
clearer code

KeyRange keys(T)(T[] t) { return KeyRange(t.length); }
alias keys = object.keys; // also bring in the runtime library's 
keys for AA; this line lets both work together in the same module 
without name conflicts

void main()
	int[] x = [0, 2];
	int y = 1;
	writeln(y in x.keys); // works!
	writeln(y+5 in x.keys); // this too

The language features used there are UFCS (allowing x.keys), 
operator overloading (opBinaryRight), and overload set merging 
(the alias line with the comment). Searching those terms on this 
website should give more information if you'd like to learn more.

More information about the Digitalmars-d mailing list