D 中的斐波那契生成器,std.concurrency.Generator

fibonacci generator in D with std.concurrency.Generator

我需要在 D 中编写斐波那契数列(从 a,b 开始)生成器, 我看过这里的例子:

https://dlang.org/library/std/concurrency/generator.html

import std.concurrency;
import std.stdio;


void main()
{
    auto tid = spawn(
{
        while (true)
        {
           writeln(receiveOnly!int());
        }
    });

    auto r = new Generator!int(
    {
        foreach (i; 1 .. 10)
            yield(i);
    });

    foreach (e; r)
    {
        tid.send(e);
    }
}

但是现在我不知道如何调用我写的生成器:

import std.concurrency;
import std.stdio;
import std.conv;
import std.string;

void main()
{
    writeln("Enter a then b");
    auto a_str = readln.strip;
    auto b_str = readln.strip;
    int a = to!int(a_str,16);
    int b = to!int(b_str,16);


    auto tid = spawn(
    {
        while (true)
        {
            writeln(receiveOnly!int());
        }
    });

    auto fib = new Generator!int(
    {
            yield(a);
            yield(b);
            while(true){
            int temp = b;
            b = a+b;
            a = temp;
            yield(b);
            }
    });

}

谢谢。

您可以使用 foreach 循环遍历生成器:

foreach (n; fib) {
    writefln("%d\n", n);
}

在您的情况下,它会一直屈服,因此出于测试目的,您可以设置一个计数器。

顺便说一句,我也在上同样的课程:)