DMD 0.170 release

Sean Kelly sean at f4.ca
Tue Oct 17 06:02:24 PDT 2006


Ary Manzana wrote:
> Walter Bright wrote:
>> Walter Bright wrote:
>>> Added foreach_reverse, which addresses a serious shortcoming.
>>>
>>> http://www.digitalmars.com/d/changelog.html
>>
>>
>> Lots of background for the foreach improvements in:
>>
>> http://www.digitalmars.com/d/archives/digitalmars/D/17320.html
> 
> What about trees? Now I want foreach_inorder, foreach_preorder and 
> foreach_postorder. :-)

You know I was thinking about this a bit last night, but couldn't come 
up with a good syntax.  But the basic idea was that since "for each" 
doesn't imply an order in which elements will be visited, perhaps the 
order could somehow be specified separately from the 'foreach' symbol. 
However, for classes an obvious alternative would be to use proxy 
objects, similar to iterators, that expose the correct algorithm in 
their opApply.

> What about classes having a function that returns the "opApply" needed? 
> Something like this:
> 
> ---
> class Tree {
>     
>     int delegate(int delegate(inout int)) inorder() {
>         return delegate int(int delegate(inout uint) dg) {
>             // inorder traversal
>         };
>     }
> 
>         int delegate(int delegate(inout int)) preorder() {
>         return delegate int(int delegate(inout int) dg) {
>             // preorder traversal
>         };
>     }
> 
>         int delegate(int delegate(inout int)) postorder() {
>         return delegate int(int delegate(inout int) dg) {
>             // postorder traversal
>         };
>     }
> 
>     // This still works, it is the default traversal
>         int opApply(int delegate(inout int) dg) {
>         // default traversal
>     }
>     
> }
> 
> void main() {
>     Tree t = giveMeSomeTree();
>     
>     foreach(int i : t.inorder) {
>         // something
>         }
> 
>     foreach(int i : t.preorder) {
>         // something
>         }
> 
>     foreach(int i : t.postorder) {
>         // something
>         }
> 
>     foreach(int i : t) {
>         // something
>         }
> 
> }
> ---
> 
> Could something like this be done? I think it has the clearest syntax: 
> no new keywords needed and very flexible. The compiler should check that 
> the right side of the foreach is an array, or a class or struct having 
> opApply, or a delegate of the singature I mentioned before.

Yeah, something like that :-)


Sean



More information about the Digitalmars-d-announce mailing list