Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A solution (modified to return 11 instead of 10 in the range) from
- // http://tour.dlang.org/tour/basics/13
- import std.stdio;
- struct FibonacciRange
- {
- auto lastButTwo = 0;
- auto lastButOne = 0;
- auto last = 0;
- @property empty() const
- {
- // So when does the Fibonacci sequence
- // end?!
- return false;
- }
- void popFront()
- {
- lastButTwo = lastButOne;
- lastButOne = last;
- }
- int front()
- {
- if (lastButTwo == 0)
- {
- last = 1;
- }
- else
- {
- last = lastButOne + lastButTwo;
- }
- return last;
- }
- }
- void main() {
- import std.range: take;
- import std.array: array;
- // Let's test this FibonacciRange!
- FibonacciRange fib;
- // The magic function take creates another
- // range which just will return N elements
- // at maximum. This range is _lazy_ and just
- // touches the original range if actually
- // needed (iteration)!
- auto fib11 = take(fib, 11);
- // But we do want to touch all elements and
- // convert the range to an array of integers.
- int[] the11Fibs = array(fib11);
- writeln("Your first 11 Fibonacci numbers: ",
- the11Fibs);
- assert(the11Fibs ==
- [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement