Following is the code for a more generalized Fibonacci range.

Questions:

1. How do I get only the value of the Nth (i.e. N = 25) element in an idiomatic way?

2. Can I set constraints in the range so that user gets warning if he asks for Nth element greater than a limit, say N> 30; or if the actually range value at N is greater than datatype limit (e.g. max long)? Maybe this should be done outside of the range, i.e. do check before accessing the range?

    #!/usr/bin/env rdmd
    import std.stdio : writeln;
    long multifactor = 4;
    int elemth = 25;

    struct FibonacciRange
    {
      long first = 1;
      long second = 1;

      bool empty() const @property
      {
       // how to stop at n = 30?
        return false;
      }

      void popFront()
      {
        long tmp = 0;
        tmp = first*multifactor + second;
        first = second;
        second = tmp;
      }

      long front() const @property
      {
        return first;
      }
    }

    void main()
    {
        import std.range : take;
        import std.array : array;

        FibonacciRange fib;

        auto fib10 = take(fib, elemth);
        long[] the10Fibs = array(fib10);
    }

Reply via email to