Get n-th
Jonathan M Davis
jmdavisProg at gmx.com
Tue Feb 22 20:00:57 PST 2011
On Tuesday 22 February 2011 18:07:46 bearophile wrote:
> Do you know a much nicer way to take just the n-th item of a lazy range?
>
>
> import std.stdio, std.array, std.range;
> void main() {
> auto fib = recurrence!("a[n-1] + a[n-2]")(1, 1);
> writeln(array(take(fib, 10)).back);
> }
>
> In Python I use next(isslice(x, n, n+1)):
> >>> from itertools import islice
> >>> r = (x*x for x in xrange(10)) # lazy
> >>> next(islice(r, 5, 6))
>
> 25
>
> Bye,
> bearophile
Assuming that it's a forward range rather than an input range:
auto s = range.save;
s.popFrontN(n - 1);
writeln(s.front);
The problem is that you have to process a lazy range before you can get at any
of its elements, and once you've processed an element, it's no longer in the
range. So, you pretty much have to save the range and operate on a copy of it.
At that point, you can remove the elements prior to the one you care about and
then take the one you care about from the front of the range.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list