range practicle use
Robert Jacques
sandford at jhu.edu
Thu Dec 30 08:02:58 PST 2010
On Thu, 30 Dec 2010 05:41:18 -0700, spir <denis.spir at gmail.com> wrote:
> Hello,
>
>
> In the course of a project (1) 2 partner D programmers and myself are
> currently implementing, we faced 2 issues which prevented us using a
> range interface as planned. We initially intended to do it for better
> compliance with D's coming new style, and nice inter-relation with
> Phobos modules like std.algorithm. Instead, we use opApply to implement
> traversal; which does the job.
> This post's purpose is to expose these problems to help and making range
> interfaces better usable, or simply usable, in various practical cases.
> (Opinions are mine --I don't known my partners' exact position, except
> that they indeed agree these topics plainly prevent us using ranges.)
> To illustrate the situation, please see an artificial example coded
> below (the real case would require explaining several irrelevant points).
>
>
> -1- textual output
[snip]
I too have been bitten by this bug. Specifically, when using opDispatch
you have to remember to disable all of the range interfaces.
> -2- indexed iteration
>
> It seems there is no way to directly define indexed iteration using
> ranges, like commonly needed by:
> foreach(index,element ; collection) {...}
>
> A possible but inadequate workaround would be to define a tool type for
> this:
> struct TraversalPair (Element) {uint index ; Element element;}
> Then define the range's element output routines (opIndex, front, back)
> to return pairs instead of elements; and use this like:
> foreach (pair ; collection) {actWith(pair.element, pair.index);}
> But this requires a client programmer to know this particularity; and
> anyway does not fit D common style and practice, I guess.
>
> How to solve this practically? I would be happy with the above
> workaround if it became a commonly used solution, supported by the
> stdlib and if necessary by the core language. This may scale by defining
> the tool type as a superclass instead, allowing various variants,
> possibly with more elements.
> Maybe an alternative is to use tuples: allow variants of opIndex, front,
> and back, to return (index,element) tuples and let the compiler use
> these overloads when the client code requests 2 (or more) returned
> values.
> The first solution is more explicite, and possibly general; the second
> may fit common practice better if/when tuples become widely used (a
> rather far & hypothetical future ;-) ?).
>
>
> Thank you,
> Denis
I'd prefer the tuple solution, particularly as tuples + syntactic sugar
have been discussed before regarding multiple value return.
More information about the Digitalmars-d
mailing list