On Tuesday, 5 August 2014 at 01:23:19 UTC, Andrew Edwards wrote:
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?

I'd use std.algorithm.until:

   void main()
   {
     import std.algorithm, std.range, std.stdio;

     auto fib_until_50k = recurrence!("a[n-1] + a[n-2]")(1, 1)
                         .until!(a => a > 50_000);
        
     writeln(fib_until_50k);
   }

Reply via email to