www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Automatic opApply iteration counter

This thread is now fit for D.learn, but I answer it here to not split it up.

Steven Schveighoffer:

 Don't forget, opApply is just a function, you can use it as such :)

Right, I forget it often... I will keep in mind your example, thank you.
 Oh, and don't forget to always make opApply take a scope delegate!  
 Otherwise, it allocates the calling function's frame on the heap (in D2 at  

To test it, I have compiled this program with and without the two scope annotations (I use printf to remove lot of noise from the resulting asm, because writeln adds tons of functions): import std.c.stdio: printf; alias int Int; struct Xfibonacci { Int max; int opApply(scope int delegate(ref Int) dg) { int _dg(ref int i, ref Int l) { return dg(l); } return opApply(&_dg); } int opApply(scope int delegate(ref int, ref Int) dg) { int result, index; Int 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; } } void main() { foreach (f; Xfibonacci(200)) printf("%d\n", f); printf("\n"); foreach (i, f; Xfibonacci(200)) printf("%d %d\n", i, f); } This is one of the functions, using the scope attributes: _D11xfibonacci210Xfibonacci7opApplyMFMDFKiZiZi: push EAX mov ECX,offset FLAT:_D11xfibonacci210Xfibonacci7opApplyMFMDFKiZiZi3_dgMFKiKiZi mov EAX,0[ESP] push ECX lea EDX,4[ESP] push EDX call near ptr _D11xfibonacci210Xfibonacci7opApplyMFMDFKiKiZiZi pop ECX ret 8 The same function, not using the scope attributes: _D11xfibonacci210Xfibonacci7opApplyMFDFKiZiZi: push EAX push EBX push ESI push 010h call near ptr __d_allocmemory mov EBX,EAX mov EAX,0Ch[ESP] mov [EBX],EAX mov EDX,018h[ESP] mov ESI,014h[ESP] mov 8[EBX],ESI mov ECX,offset FLAT:_D11xfibonacci210Xfibonacci7opApplyMFDFKiZiZi3_dgMFKiKiZi mov 0Ch[EBX],EDX add ESP,4 push ECX push EBX call near ptr _D11xfibonacci210Xfibonacci7opApplyMFDFKiKiZiZi pop ESI pop EBX pop ECX ret 8 Bye, bearophile
Apr 14 2010