Proposal: Hide the int in opApply from the user

Bill Baxter dnewsgroup at billbaxter.com
Mon Jan 7 10:56:38 PST 2008


Sean Kelly wrote:
> Jason House wrote:
>> I think this proposal has one fatal flaw...
>>
>> There is no way for the opApply function to do something after 
>> iteration stops prematurely.  Some data structures could change 
>> internal state as they iterate.  Those state changes may require 
>> clean-up.  I have no good examples at the moment, but know they exist.

Hmm, you're right.  That's an issue that had not occurred to me because 
I've never seen it in code.  But it's not a fatal flaw I do not think.

The yield thing is a pretty trivial macro.  I see several possible ways 
to handle such rare cases.

1) Add public opCall and a public 'finished' methods to Apply to allow 
users to do yield's work on their own:

struct Apply(Args...) {
     // .. same as before plus:
     void opCall(Args args) { _loop_body(args); }
     bool finished() { return *_ret!=0; }
}

Then this is possible:

void opApply( Apply!(ref T) dg ) {
    for( /*T x in elements*/ ) {
        dg(x);
        if (dg.finished) {
            // do clean up;
            return;
        }
    }
}


2) Provide an alternate macro that takes a cleanup parameter:

void opApply( Apply!(ref T) dg ) {
    for( /*T x in elements*/ ) {
        yield_with_cleanup(dg, { /*do cleanup*/ }, x);
    }
}


3)
> scope(exit) would work, but it's not ideal.

But it's probably the solution that I would use, and one of the other 
solutions can be used for what I expect are the very rare situations in 
which you both have to do clean up in your opApply and for some reason 
can't use scope(exit).


--bb



More information about the Digitalmars-d mailing list