www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Testing membership in associative array

reply Lettever <real email.com> writes:
I am trying to create a function that tests membership in nested 
associative array, however the function I create below, only 
accepts keys of the same type and if given keys of different 
types it does not compile, help would be appreciated.
This is a example of what Im talking about.
```d
import std.stdio;
void main()
{
     int[int][int] aa1;
     aa1[1][2] = 3;
     writeln(contains(aa1, 1, 2));   //returns true as expected
     int[int][string] aa2;
     aa2["1"][2] = 3;
     writeln(contains(aa2, "1", 2)); //does not compile because of 
this line
}
bool contains(M, K...)(M map, K keys)
{
     foreach(key; keys)
         if(key in map)
             return contains(map[key], keys[1 .. $]);
         else
             return false;
     return true;
}
```
Mar 04
parent reply Profunctor <profunctor example.com> writes:
On Monday, 4 March 2024 at 23:49:46 UTC, Lettever wrote:
 [ ... ]
```d // A template constraint is added to ensure we may always index into `keys`, // in addition to being a sanity check. bool contains(M, K...)(M map, K keys) if (K.length > 0) { static if (K.length == 1) return (keys[0] in map) !is null; else return contains(map[keys[0]], keys[1 .. $]); } ``` One might also be interested in adding a static assert or template constraint ensuring the number of keys passed are less than or equal to the nested-ness of the associated array.
Mar 04
parent Profunctor <profunctor example.com> writes:
My sincerest apologies, my initial solution is flawed due to a 
foolish oversight. The below version works.

```d
bool contains(M, K...)(M map, K keys)
if (K.length > 0) {
   static if (K.length == 1)
     return (keys[0] in map) !is null;
   else
     return (keys[0] in map) !is null && contains(map[keys[0]], 
keys[1 .. $]);
}
```
Mar 04