On 2008-Dec-4, at 9:09 am, Aristotle Pagaltzis wrote:
And while it does seems like a closure trait, that seems somewhat problematic in that the order of evaluation is weird when compared to other closure traits, which I suppose is what led you to declare the “coy” solution as the most natural.


I tried to break down the reasons for wanting to write such loops different ways:

1) Simple code -- the "coy" solution, with the condition checked in the middle of the loop, is the cleanest in that if we put the condition anywhere else, we still also need to mark where in the middle it should be checked.

2) Clear code -- putting the condition up front (or maybe at the end) makes it stand out and more clearly identifies the purpose of the loop. Of course, you still need something in the middle as well as up front, so you could simply put a comment up front to explain what's going on.

3) Self-documenting code -- this is different from the previous point (introspection rather than [non-self] documentation... like my other comment about counting iterations -- you can always add "$i++; #to check for second loop", but then the meaning is accidental rather than implicit). I think this gets at the heart of the problem: not merely making code do the right thing, but making it "look" the right way, making it use a natural idiom. So something like:

        repeat using $block
        {
                something();
                
                check-condition;
                # means: last unless $block;
                
                something_else();
        }

But I don't really like the need to add the "check-condition" command.
Maybe something like:

        repeat using <LABEL>
        {
                something();
                
                LABEL: last unless $block;
                
                something_else();
        }


But that still seems too sloppy. What we need is something a bit like the "continue" block, except that it gets executed before the loop- condition is checked the first time. So what if we split the loop- body into two parts?

        repeat { something(); }
                while ( condition(); )
                        { something_else(); }


Now the condition is in the middle and is syntactically separate. (It's still not up front, but if the first block is really long, you can always... add a comment!)


-David

Reply via email to