D Recurrences

Timon Gehr timon.gehr at gmx.ch
Thu Jun 9 08:40:01 PDT 2011


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;
> }

You use the function recurrence incorrectly in the second example: You may only
use a[n-1] to a[n-x] in your formula where x is the number of arguments given to
the template function. It would be nice if the library could enforce this, but (at
least currently) it cannot.


Timon


More information about the Digitalmars-d mailing list