'in' syntax for searching arrays

Janice Caron caron800 at googlemail.com
Sun Nov 4 00:06:59 PDT 2007


How coincidental. Only yesterday (on another thread) I posted my
thought that it would be cool to have a std.array module with lots of
array functions, with as much power as those of PHP (though not with
the same syntax!)

My own thought is that looking for values in arrays should have the
same syntax as strings. That is, for non-associative arrays:

V[] a;
int n = a.find(x);

should return -1 if the value is not present in the array, or the
index if it is. This is a much better idea than returning a pointer to
the element, because (a) you don't have to worry about const and
invariant, and (b) it's the same as std.string. In addition, you can
then do a[n..$].find() to find the second occurence, and so on.

For associative arrays, it's trickier to decide on the syntax. My
first thought was

V[K] a;
K n = a.find(x); // return a key whose value is x

but that doesn't really work so well. First, there's no generic
equivalent to -1, and hence no way to say "no match". Second, there's
no real way of searching for the second match, once you've found the
first. So then, my second thought was, maybe it should be

V[K] a;
K[] n = a.findAll(x); // return an array of all keys whose value is x

PHP has a function which "filps" an array, so that keys become values
and values become keys. That would be useful too.



More information about the Digitalmars-d mailing list