www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Create a foreach-able struct? Multi-dimensional even?

reply Heywood Floyd <soul8o8 gmail.com> writes:
Hello!

1) How do I create a struct that I can foreach over?

I get the impression opApply has something do to with this, but I can't find
any documentation on it? (And I'm abroad without my TDPL.)


2) Also, is it possible to do something like this? 

  MyData!(100,100,100) data;
  foreach(x, y, z, ref cell; data){
     cell = x*y*z;
  }

(The idea here is cells are stored in a plain 1-dimensional array behind the
scenes, but iterated as a 3-dimensional array.)


Kind regards
/HF
Aug 25 2011
parent reply Heywood Floyd <soul8o8 gmail.com> writes:
Heywood Floyd Wrote:

 
 Hello!
 
 1) How do I create a struct that I can foreach over?
 
 I get the impression opApply has something do to with this, but I can't find
any documentation on it? (And I'm abroad without my TDPL.)
 
 
 2) Also, is it possible to do something like this? 
 
   MyData!(100,100,100) data;
   foreach(x, y, z, ref cell; data){
      cell = x*y*z;
   }
 
 (The idea here is cells are stored in a plain 1-dimensional array behind the
scenes, but iterated as a 3-dimensional array.)
 
 
 Kind regards
 /HF

Ah, I'm sorry, I found the documentation regarding opApply() now. Typical. (The site-search didn't seem to work there. Ok..) Still, is the multi-dimensional part possible? /HF
Aug 25 2011
parent reply travert phare.normalesup.org (Christophe) writes:
 Still, is the multi-dimensional part possible?

Sure, you have to make an opApply that takes several parameters in its delegate. An exemple: struct TwoDArray(int nx, int ny) { int[nx][ny] data; int opApply(int delegate(ref int i, ref int j, ref int cell) { foreach (i; 0..nx) foreach (j; 0..ny) { int result = dg(i, j, data[i][j]); if (result != 0) return result; } return 0; } } // this program prints a multiplication table: int main() { TwoDArray!(10, 10) data; foreach(i, j, ref cell; data) { cell = i * j; } foreach(i, j, cell; data) { writefln("%s * %s = %s", i, j, cell); } return 0; }
Aug 25 2011
parent Heywood Floyd <soul8o8 gmail.com> writes:
Christophe Wrote:

 Still, is the multi-dimensional part possible?

Sure, you have to make an opApply that takes several parameters in its delegate. An exemple: struct TwoDArray(int nx, int ny) { int[nx][ny] data; int opApply(int delegate(ref int i, ref int j, ref int cell) { foreach (i; 0..nx) foreach (j; 0..ny) { int result = dg(i, j, data[i][j]); if (result != 0) return result; } return 0; } } // this program prints a multiplication table: int main() { TwoDArray!(10, 10) data; foreach(i, j, ref cell; data) { cell = i * j; } foreach(i, j, cell; data) { writefln("%s * %s = %s", i, j, cell); } return 0; }

Ha! Beautiful, thanks!!
Aug 25 2011