Thread overview
Testing membership in associative array
Mar 04
Lettever
March 04

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.

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;
}
March 05

On Monday, 4 March 2024 at 23:49:46 UTC, Lettever wrote:

>

[ ... ]

// 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.

March 05

My sincerest apologies, my initial solution is flawed due to a foolish oversight. The below version works.

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 .. $]);
}