Taking from infinite forward ranges
Andrew Edwards via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Aug 4 18:23:18 PDT 2014
Is there a way to take a bounded rage from a infinite forward range?
Given the Fibonacci sequence:
auto fib = recurrence!("a[n-1] + a[n-2]")(1, 1);
I can take the first n elements:
take(fib, 10);
But say I want all positive elements below 50000 in value (there are
eight such values [2, 8, 34, 144, 610, 2584, 10946, 46368]), how would I
"take" them? Of course I could filter the range, leaving only positive
values, and then take(fib, 8). But what if I didn't know there were 8,
how could I take them from there filtered range?
Currently I do this:
foreach(e; fib)
{
if (e >= val) break;
// so something with e
}
or
while((e = fib.front()) < n)
{
// do something with e
fib.popFront();
}
Is there a better way?
More information about the Digitalmars-d-learn
mailing list