Should range foreach be iterating over an implicit copy?
Ken
kennethuil at gmail.com
Thu Jun 7 18:51:42 PDT 2012
On Friday, 18 May 2012 at 06:17:13 UTC, Lars T. Kyllingstad wrote:
> On Thursday, 17 May 2012 at 14:18:55 UTC, Steven Schveighoffer
> wrote:
>> [...] I believe someone has created a byRef struct that wraps
>> a range and iterates it byRef (maybe dsimcha?)
>
> Nope, me. :)
>
> https://github.com/kyllingstad/ltk/blob/master/ltk/range.d#L12
>
> It only supports the input range primitives, because that was
> all I needed when I wrote it. I offered to contribute it to
> Phobos (with support for the remaining range types, of course),
> but the interest for it seemed rather low.
>
> -Lars
I've got a use for it right now. I've implemented groupBy for my
project, which is like std.algorithm.group except that instead of
giving you the number of adjacent equivalent items, it gives you
a lazy subrange of them. So you end up with a range of subranges.
Trouble is, if you feed the inner range to foreach, it works on a
copy of the inner range. Which means that the outer range skips
through the entire inner range you just iterated through in order
to get to the next inner range.
Now if the range you feed to groupBy is a true non-ForwardRange,
where copying it just creates an alias of some kind, this problem
goes away. Your wrapper looks like it would do the trick there.
At any rate, the whole thing makes an excellent use case for
foreach(ref e; ref r).
More information about the Digitalmars-d
mailing list