Automatic opApply iteration counter
Steven Schveighoffer
schveiguy at yahoo.com
Tue Apr 13 03:13:37 PDT 2010
bearophile Wrote:
> I have not written this as enhancement request on Bugzilla because while I have a clear (small) problem, I think my possible solution is bad (see at the bottom).
>
[snip]
> To allow both the foreach version with and without index I have to duplicate the body of the opApply, but this code duplication is bad:
No. This is how I do it in dcollections (for optional keys in map containers):
> import std.stdio: writeln;
> struct Xfibonacci {
> long max;
> this(long inmax) { max = inmax; }
> int opApply(int delegate(ref long) dg) {
int _dg(ref int i, ref long l) { return dg(l); }
return opApply(&_dg);
> }
> int opApply(int delegate(ref int, ref long) dg) {
> int result, index;
> long a=0, b=1;
> while (a < max) {
> result = dg(index, b);
> if (result) break;
> index++;
> a += b;
> result = dg(index, a);
> if (result) break;
> b += a;
> index++;
> }
> return result;
> }
> }
Don't forget, opApply is just a function, you can use it as such :)
More information about the Digitalmars-d
mailing list