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

Brett Brett at gmail.com
Thu Sep 19 04:22:45 UTC 2019


On Wednesday, 18 September 2019 at 01:27:09 UTC, Adam D. Ruppe 
wrote:
> 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)
>
> Indeed.
>
> Actually, fun fact: you can do that in your own code. Write a 
> function `keys` that returns a struct implementing 
> `opBinaryRight`.
>
> 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.

Thanks. I guess I should have realize that UFCS could solve it. 
Probably should be added to phobos?


More information about the Digitalmars-d mailing list