Find if keys are in two dimensional associative array

Simen kjaeraas simen.kjaras at gmail.com
Sun Jan 17 11:48:27 PST 2010


Michal Minich <michal.minich at gmail.com> wrote:

> This is great! I was thinking such generic template would be good, but I
> did not have need for it right now.
>
> This should be definitely posted to bugzilla as enhancement for Phobos,
> and also for Tango.

Thank you. I have now improved the code to also work for normal arrays:


template elementTypeOfDepth( T : V[ K ], int depth, V, K ) {
     static if ( depth == 0 ) {
         alias V elementTypeOfDepth;
     } else {
         alias elementTypeOfDepth!( V, depth -1 )  elementTypeOfDepth;
     }
}

template elementTypeOfDepth( T : V[ ], int depth, V ) {
     static if ( depth == 0 ) {
         alias V elementTypeOfDepth;
     } else {
         alias elementTypeOfDepth!( V, depth -1 )  elementTypeOfDepth;
     }
}

elementTypeOfDepth!( T, U.length )* isIn( T : V[ ], V, U... )( T arr,  
size_t key, U index ) {
     if ( key < arr.length ) {
         auto p = arr[ key ];
         static if ( U.length > 0 ) {
             if ( p ) {
                 return isIn( p, index );
             } else {
                 return null;
             }
         } else {
             return p;
         }
     } else {
         return null;
     }
}

elementTypeOfDepth!( T, U.length )* isIn( T : V[ K ], V, K, U... )( T arr,  
K key, U index ) {
     auto p = key in arr;
     static if ( U.length > 0 ) {
         if ( p ) {
             return isIn( *p, index );
         } else {
             return null;
         }
     } else {
         return p;
     }
}

Usage:
int[char][][int] foo;
if ( isIn( foo, 3, 87, 'a' ) ) {
     writeln( "Excelsior!" );
}

> I was thinking this also may be solved by modification in language:
>
> the problem with statement "123 in *('a' in aa)" is that if "('a' in
> aa')" returns null, then next check will fail: (123 in null) -> null
> reference error.
>
> if D simply check if the second part of InExpression is null, and if yes,
> return null, otherwise evaluate as is currently done.

This sounds good. Put it in Bugzilla.

-- 
Simen


More information about the Digitalmars-d-learn mailing list