foreach, an analogy
Benji Smith
dlanguage at benjismith.net
Wed Oct 25 15:45:50 PDT 2006
clayasaurus wrote:
> Here is my view on foreach_reverse
>
> 1) I really like the idea of foreach being the defacto-iterator for D
Me too.
> 2) foreach_reverse allows me to implement an opApply function to my
> doubly linked list template for not only forward iteration, but
> backwards iteration as well! Otherwise, I'd have to pass it a
> &list.reverse delegate which is hackish.
In C#, the foreach construct operates over arrays or objects that
implement the IEnumerable<T> interface (which includes the
ICollection<T> subinterface).
In Java, the "enhanced for loop" operates over arrays or objects that
implement the Iterable<T> interface (which includes the Collection<T>
sub-interface).
As far as I'm concerned, each class should be responsible for
determining which iterators it offers. A doubly-linked list could provide:
DoublyLinkedList.getForwardIterator();
DoublyLinkedList.getReverseIterator();
Whereas a binary tree might provide even more:
BinaryTree.getInOrderIterator();
BinaryTree.getReverseOrderIterator();
BinaryTree.getDepthFirstIterator();
BinaryTree.getBreadthFirstIterator();
Then, the foreach just iterates through any object that's iterable. Like
this:
IEnumerable<T> iterator = myBinaryTree.getDepthFirstIterator();
foreach(T item in iterator) {
// do stuff with item
}
A single mechanism for all different kinds of iteration scenarios.
The ECMA C# specification (starting on page 236) gives a thorough
description of how compilers should implement foreach:
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
I think it's a very elegant solution.
In D, even overlooking the presence of a fifteen-letter keyword
("foreach_reverse"), the ugliest part is the presence of the
opApplyReverse() method, which suggests that the collection object
should be responsible for its own iteration, whereas I think iteration
should be delegated to a separate object.
--Benji Smith
More information about the Digitalmars-d-announce
mailing list