26

C# の単純なジェネレーターを次に示します。

    IEnumerable<int> Foo()
    {
        int a = 1, b = 1;
        while(true)
        {
            yield return b;
            int temp = a + b;
            a = b;
            b = temp;
        }
    }

Digital Mars Dで同様のジェネレータを作成するにはどうすればよいですか?

(質問はyield returnステートメントについてです)

ありがとう!


アップデート。それは面白い。数学的シーケンスを生成しているだけなので、繰り返しを使用するのが良いオプションかもしれません。

auto fib = recurrence!("a[n-1] + a[n-2]")(1, 1);

foreach (e; take(fib, 10)) // <- prints first ten numbers from the sequence
{ 
    writeln(e); 
}
4

3 に答える 3

20

ここを参照してください; 以下の抜粋例:

module main;

import std.stdio;
import generators;

void genSquares(out int result, int from, int to)
{
    foreach (x; from .. to + 1)
        yield!result(x * x);
}

void main(string[] argv)
{
    foreach (sqr; generator(&genSquares, 10, 20))
        writeln(sqr);
}
于 2011-07-16T06:35:24.623 に答える
20

D には正確に相当するものはありません。大まかに相当するものを次に示します。

opApply スタイルの内部反復を使用します。ただし、これはロックステップで 2 つの反復子を反復することを許可しません。

struct Foo {
    int opApply(int delegate(ref int) dg) {
        int a = 1, b = 1;
        int result;
        while(true) {
            result = dg(b);
            if(result) break;
            int temp = a + b;
            a = b;
            b = temp;
        }

        return result;
    }
}

void main() {
    // Show usage:
    Foo foo;
    foreach(elem; foo) {
        // Do stuff.
    }
}

範囲を使用します。場合によっては、これらを記述するのが少し難しくなりますが、非常に効率的で、ロックステップの反復が可能です。これは、バージョンforeachとまったく同じように、ループで繰り返すこともできます。opApply

struct Foo {
    int a = 1, b = 1;

    int front() @property {
        return b;
    }

    void popFront() {
        int temp = a + b;
        a = b;
        b = temp;
    }

    // This range is infinite, i.e. never empty.
    enum bool empty = false;

    typeof(this) save() @property { return this; }
}

本当にコルーチン スタイルのものが必要な場合は、 を使用して range と opApply を組み合わせることができcore.thread.Fiberますが、ほとんどの場合、ranges または opApply のいずれかが必要なことを実行することに気付くでしょう。

于 2010-10-04T16:54:28.860 に答える
17

std.concurrencyモジュールには、これをさらに簡単にするクラスGeneratorがあります (サードパーティのライブラリは必要ありません)。

クラスは入力範囲なので、 for ループとすべての標準std.range/std.algorithm関数で使用できます。

import std.stdio;
import std.range;
import std.algorithm;
import std.concurrency : Generator, yield;

void main(string[] args) {
    auto gen = new Generator!int({
        foreach(i; 1..10)
            yield(i);
    });

    gen
        .map!(x => x*2)
        .each!writeln
    ;
}
于 2015-06-24T14:15:50.133 に答える