yield, C# etc

bearophile bearophileHUGS at lycos.com
Wed Aug 13 04:49:58 PDT 2008


Denis Koroskin:
> I don't see much difference between "yield return i;" and "int result =  
> dg(i);".
> First one is slightly cleaner while second one allows overloading.

You are right, probably I prefer Python semantics & syntax here, not C# (or D) ones. I most of the cases you don't need overloading, but you always want a nicer syntax. (For people coming from C++ syntax is less important, I know).


> Everything else is an implementation details.

Syntax matters, when you have recursive generators every bit of help you receive from the language is precious to avoid distracting you from messing the algorithm.
The current syntax of D for the lazy iteration is very bad.

The following series generates the inverse Gray code:
http://www.research.att.com/projects/OEIS?Anum=A006068


In Python:

def A006068():
    yield 0
    for x in A006068():
        if x & 1:
            yield 2*x+1
            yield 2*x
        else:
            if x:
                yield 2*x
            yield 2*x+1


In D using my libs, that use code modified from Witold Baryluk:

struct A006068 {
    void generator() {
        yield(0);
        foreach(x; A006068()) {
            if (x & 1) {
                yield(2 * x + 1);
                yield(2 * x);
            } else {
                if (x)
                    yield(2 * x);
                yield(2 * x + 1);
            }
        }
    }
    mixin Generator!(int);
}


In normal D:

struct A006068b {
    int opApply(int delegate(ref int) dg) {
        int result, aux;
        aux = 0; result = dg(aux); if (result) return result;
        foreach(x; A006068b()) {
            if (x & 1) {
                aux = 2 * x + 1; result = dg(aux); if (result) break;
                aux = 2 * x; result = dg(aux); if (result) break;
            } else {
                if (x)
                    { aux = 2 * x; result = dg(aux); if (result) break; }
                aux = 2 * x + 1; result = dg(aux); if (result) break;
            }
        }
        return result;
    }
}

The D version is bad to read and bad to write, there's too much noise.

Bye,
bearophile



More information about the Digitalmars-d mailing list