D Recurrences

Ali Çehreli acehreli at yahoo.com
Thu Jun 9 16:10:11 PDT 2011


On Thu, 09 Jun 2011 16:19:23 +0100, Ben Grabham wrote:

> Hey,
> 
> Shouldn't both these programs output the fibonnacci numbers? Only the
> first one does.
> 
> import std.range;
> import std.stdio;
> int main() {
> 	auto a = recurrence!("a[n-1] + a[n-2]")(0,1); int i = 0;
> 	foreach(int n; a) {
> 		if(i++ > 20) break;
> 		writefln("%d", n);
> 	}
> 	return 0;
> }
> 
> 
> 
> import std.range;
> import std.stdio;
> int main() {
> 	auto a = recurrence!("a[n-1] + (n < 2 ? 0 : a[n-2])")(1); int i = 
0;
> 	foreach(int n; a) {
> 		if(i++ > 20) break;
> 		writefln("%d", n);
> 	}
> 	return 0;
> }

For what it's worth, here is a Fibonacci range. (Translated from 
D.ershane's "Aralıklar" (Ranges) chapter.)

import std.stdio;
import std.range;

struct FibonacciRange
{
    int first = 0;
    int second = 1;

    enum empty = false;

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

    void popFront()
    {
        int next = first + second;
        first = second;
        second = next;
    }

    FibonacciRange save() const
    {
        return this;
    }
}

void main()
{
    writeln(take(FibonacciRange(), 20));
}

Ali


More information about the Digitalmars-d mailing list