Last element of a forward range

monarch_dodra monarchdodra at gmail.com
Sat Apr 12 05:38:28 PDT 2014


On Saturday, 12 April 2014 at 10:27:00 UTC, bearophile wrote:
> Steven Schveighoffer:
>
>> Interesting problem.
>
> And it's not an academic one, I have already faced it two or 
> three times :-)
>
>
>> Given that it is a forward range, a zip between it and a saved 
>> copy that is advanced by one may work.
>
> This compiles and gives the expected output, but how do you 
> extract the last item with this?
>
> seq.zip(seq.dropOne).writeln;

For starters, you can't in the sense that writeln takes by value, 
and your zip has value semantics. So in fact, it is still 
unchanged. BTW: That UFCS "seq.zip(someOtherRange)": Ew.

So you'd need to start with a:
auto z = zip(seq, seq.dropOne);
while (!z.empty)
     z.popFront();

That's step one. Step two would be actually extracting the 
remainaing range. In theory, you can't. In practice, you can hack 
around the implementation by:
zip.ranges[1].front;

Turns out "ranges" is not private. I wouldn't use this.

The second, is modifying the stopping policy on the fly:
zip.stoppingPolicy = StoppingPolicy.longest;
auto a = zip.front[1];

I think both are *very* hackish.
I'd do this:

auto bck = seq.save; seq.popFront();
while (!seq.empty)
{
     bck.popFront();
     seq.popFront();
}
auto last = bck.front;


More information about the Digitalmars-d-learn mailing list