The new ?? and ??? operators

Janice Caron caron800 at googlemail.com
Wed Sep 26 02:34:36 PDT 2007


I think I've solved the problem. This works!


    int main()
    {
        int[string] aa;
        aa["B"] = 42;

        int n = firstOf("A" in aa)("B" in aa)("C" in aa)(0);
        writefln(n);

        return 0;
    }

As you'd expect, it prints 42. But wait - there's more! Just to prove
that it's not doing unnecessary work, watch this:

    int * lookup(string s, int[string] aa)
    {
        writef("(%s) ",s);
        return s in aa;
    }

    int main()
    {
        int[string] aa;
        aa["B"] = 42;

        int m = firstOf(lookup("A",aa))(lookup("B",aa))(lookup("C",aa))(0);
        writefln(m);

        return 0;
    }

This prints
(A) (B) 42.

So the third lookup is not done. Woo hoo! And all with no ?? operator.
How's it done? Well, I'll tell you. It's done like this:


    SnazzyFunctor firstOf(lazy int * p)
    {
        return new SnazzyFunctor(p);
    }

    class SnazzyFunctor
    {
        this(int * p)
        {
            result = p;
        }

        SnazzyFunctor opCall(lazy int * p)
        {
            if (result == null) result = p;
            return firstOf(result);
        }

        int opCall(lazy int n)
        {
            if (result != null) return *result;
            return n;
        }

        int * result;
    }

(I'm sure worthier minds than mine could templatise this)



More information about the Digitalmars-d mailing list