foreach, an analogy

Bill Baxter dnewsgroup at billbaxter.com
Thu Oct 19 21:45:53 PDT 2006


Karen Lanrap wrote:
> Andy Knowles wrote:
> 
> [some code]
> There are at least two bugs in your code. Stays the opApply as easy 
> if the visits must be inorder?

Yep.  (Assuming the original code worked...) in-order should just 
require swapping a few lines:

class Tree {
     Tree left;
     Tree right;
     int data;

     int opApply(int delegate(inout Tree n) dg) {
        int ret=0;
        if (left != null)
          ret = left.opApply(dg);
        if (!ret)
          ret = dg(this);
        if(!ret && right != null)
          ret = right.opApply(dg);
        return ret;
     }
}


I think this example more than anything else shows why ret must die by 
whatever means possible.  The basic algorithm is very simple but it's 
hard to see that amidst all the setting and checking and returning of 
'ret's.  And it's very easy to mess up the ret-handling logic, with the 
result being a bug you won't see until someone tries to do a goto long, 
long down the road.

>> The call stack stores our stack implicitly.
> 
> Would this be true in any case of enumeration of the tree, asuming 
> that the stored structure has indeed the property of a tree?

I don't understand your question.

--bb




More information about the Digitalmars-d-announce mailing list