Bartosz Milewski seems to like D more than C++ now :)

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Sep 20 07:48:01 PDT 2013


On Fri, Sep 20, 2013 at 05:36:59PM +0400, Dmitry Olshansky wrote:
> 20-Sep-2013 14:55, Szymon Gatner пишет:
> >On Friday, 20 September 2013 at 10:47:52 UTC, Dmitry Olshansky wrote:
> >>20-Sep-2013 14:00, Jacob Carlborg пишет:
> >>>On 2013-09-20 11:37, Szymon Gatner wrote:
> >>>
> >>>>If only std algorithms took containers (by that I mean things that
> >>>>container for accepts too) as arguments (and not iterators)...
> >>>>even in the form of new functions like foreach_all, transform_all
> >>>>etc.
> >>>
> >>>Can't a container be a range as well?

A container should not be confused with a range. That way leads to
dragons. :-P  (It's rather unfortunate that built-in arrays conflate the
two, it leads to a lot of wrong code that works only with arrays but not
with "real" ranges.)


> >>For Christ sake no, no and no. For starters range skips/drops
> >>elements when iterating, and thusly iteration has its own state that
> >>is useless for a container otherwise.
> >
> >That would be a filtering range which adds additional logic that
> >costs exactly the same as an if() statement inside a for loop when
> >filtering on condition manually.
> >
> Filtering is just an adapter.
> Better examples are traversing e.g. binary-tree depth-first
> in-order, or post-order and that would require state.
> Again it's easy to miss by looking at built-in arrays.

Traversing the tree at all requires state, whether or not you do it with
ranges. You either put the state on the runtime stack (recursion), or
you put the state on the heap in the range adaptor. Same thing.


> >>TL;DR: Suboptimal, unnatural and error prone are keywords.
> >
> >Why would it be suboptimal?
> 
> If said tree needs to be a range I would be horrified to see how it
> manges to be at the same time a range that (for the sake of example)
> traverses said tree depth-first in-order.
> 
> Not even talking about trees having no one "natural" range over them.
[...]

Some trees do, like document trees. But yeah, in general, you don't have
a natural ordering to trees.

But then again, the whole point of ranges is *linear* traversal. If
you're not doing that, then it's probably the wrong abstraction to use.
(FWIW, while SortedRange is a neat hack, I haven't actually found it
that useful in practice. Most of the ranges I actually use are for the
cases where it's an input/forward range and you don't want to store the
whole thing, so random access is impractical. The cases where I actually
have random access usually turn out to be plain ole arrays anyway, so
the SortedRange abstraction isn't really necessary.)

So for trees, I'd argue that you need a tree-specific iteration
abstraction, not ranges, which are linear. It's a clear case of
structure conflict. ;-)


T

-- 
Real Programmers use "cat > a.out".


More information about the Digitalmars-d mailing list