Advertisement
Guest User

Fibonacci Range Example

a guest
May 17th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.34 KB | None | 0 0
  1. // A solution (modified to return 11 instead of 10 in the range) from
  2. // http://tour.dlang.org/tour/basics/13
  3.  
  4. import std.stdio;
  5.  
  6. struct FibonacciRange
  7. {
  8.     auto lastButTwo = 0;
  9.     auto lastButOne = 0;
  10.     auto last = 0;
  11.    
  12.     @property empty() const
  13.     {
  14.         // So when does the Fibonacci sequence
  15.         // end?!
  16.         return false;
  17.     }
  18.  
  19.     void popFront()
  20.     {
  21.         lastButTwo = lastButOne;
  22.         lastButOne = last;
  23.     }
  24.  
  25.     int front()
  26.     {
  27.         if (lastButTwo == 0)
  28.         {
  29.             last = 1;
  30.         }
  31.         else
  32.         {
  33.             last = lastButOne + lastButTwo;
  34.         }
  35.         return last;
  36.     }
  37. }
  38.  
  39. void main() {
  40.     import std.range: take;
  41.     import std.array: array;
  42.  
  43.     // Let's test this FibonacciRange!
  44.     FibonacciRange fib;
  45.  
  46.     // The magic function take creates another
  47.     // range which just will return N elements
  48.     // at maximum. This range is _lazy_ and just
  49.     // touches the original range if actually
  50.     // needed (iteration)!
  51.     auto fib11 = take(fib, 11);
  52.  
  53.     // But we do want to touch all elements and
  54.     // convert the range to an array of integers.
  55.     int[] the11Fibs = array(fib11);
  56.  
  57.     writeln("Your first 11 Fibonacci numbers: ",
  58.         the11Fibs);
  59.     assert(the11Fibs ==
  60.         [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement