foreach iterator with closure

Denis noreply at noserver.lan
Sun Jun 28 03:19:11 UTC 2020


Is it possible to write an iterator that does the following, 
using a struct and some functions?

  - Operates in a foreach loop
  - Has BEGIN-like and END-like blocks or functions that are 
executed automatically, before and after the iterations
  - Initializes variables in the BEGIN block that are used in the 
other two. These variables are for internal use only, i.e. must 
not be accessible to the user of the foreach loop

I'd like to use the simplest solution while keeping the code 
clean. As a starting point, here's a contrived example using a 
struct with a range-style iterarator:

   import std.stdio;

   struct letters {
     string str;
     int pos = 0;
     char front() { return str[pos]; }
     void popFront() { pos ++; }
     bool empty() {
       if (pos == 0) writeln(`BEGIN`);
       else if (pos == str.length) writeln("\nEND");
       return pos == str.length; }}

   void main() {
     foreach (letter; letters(`hello`)) {
       write(letter, ' '); }
     writeln(); }

The obvious problems with this code include:

(1) The user can pass a second argument, which will set the 
initial value of pos. This must not be allowed. (The real code 
will need to initialize a half dozen internal-only variables, and 
do some additional work, before the looping starts.)

(2) Sticking the code for the BEGIN and END blocks into the 
empty() function is ugly.

Can this iterator be written using a range-style struct? Or is 
something more complicated needed, like an OO solution?

I should add that the final version of this will be put in a 
separate module, possibly in a library, so I can call it from 
many programs. Not sure if that might help simplify things.

Thanks for your guidance.


More information about the Digitalmars-d-learn mailing list