yield, C# etc
downs
default_357-line at yahoo.de
Thu Aug 14 05:59:01 PDT 2008
bearophile wrote:
> 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);
> }
>
FWIW, in tools:
module test92;
import tools.stackthreads, tools.log;
Source!(int) A006068() {
return new Source!(int)((void delegate(int) yield) {
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);
}
}
});
}
void main() { foreach (v; A006068()) logln(v); }
Also .. is it expected that this does an infinite loop?
More information about the Digitalmars-d
mailing list