AA keys

bearophile bearophileHUGS at lycos.com
Mon Mar 17 09:21:06 PDT 2008


Frits van Bommel Wrote:
> Of course, you could implement them and attach the patch to the relevant 
> bug report... which didn't exist yet.
> Remedied that last part:
> Phobos: <http://d.puremagic.com/issues/show_bug.cgi?id=1926>
> Tango: <http://www.dsource.org/projects/tango/ticket/988>

You are good.
For reference this is the equalAA in my libs you can find online:


/***************************************
The == among two AAs.

DMD V.1.015 doesn't define < <= == != >= > among AAs.
(Python defines them all among dicts, so a full cmpAA can be defined too).
*/
bool equalAA(TyK1, TyV1, TyK2, TyV2)(TyV1[TyK1] aa1, TyV2[TyK2] aa2) {
    static if( !is(TyK1 == TyK2) || !is(TyV1 == TyV2) )
        return false;
    else {
        if (aa1.length != aa2.length)
            return false;

        foreach(k, v; aa1) {
            auto k_in_aa2 = k in aa2;
            if (!k_in_aa2 || (*k_in_aa2 != v))
                return false;
        }

        return true;
    }
}

unittest { // Test of equalAA()
    assert(  equalAA(AA!(int, int), AA!(int, int)) );
    assert( !equalAA(AA!(char, int), ['a':2, 'b':3]) );
    assert( !equalAA(['a':2, 'b':3], AA!(char, int)) );
    assert( !equalAA(['a':2, 'b':3], AA!(int, int)) );
    assert(  equalAA(['a':2, 'b':3], ['a':2, 'b':3]) );
    assert( !equalAA(['a':2, 'b':3], ['a':2]) );
    assert( !equalAA(['a':2, 'b':3], ['a':2, 'b':3, 'c':1]) );
    assert( !equalAA(['c':2, 'b':3], ['a':2, 'b':3]) );
    assert( !equalAA(['a':3, 'b':3], ['a':2, 'b':3]) );
    assert( !equalAA([2:'a', 3:'b'], ['a':2, 'b':3]) );
}

(AA!() creates an empty AA array).
Note it may not work if keys and/or values are static arrays (it can be modified in an ugly way to work in such situation too)
(Note that is gives false if the items are of different type, even if they can be cast-converted to each other. This may be different from arrays.)

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list