本文介绍了什么是“收益率回报"?等价于D编程语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C#中的简单生成器.

Here is a simple generator in 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中编写类似的生成器?

How do I write a similar generator in Digital Mars D?

(问题与收益率回报语句有关)

谢谢!

更新.那很有意思.由于我只是在生成数学序列,因此使用 重复 可能是一个不错的选择.

Update.That's interesting. Since I'm just generating a mathematical sequence, using recurrence may be a good option.

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

推荐答案

D中没有 exact 等效项.以下是一些粗略的等效项:

There's no exact equivalent in D. Here are some rough equivalents:

使用opApply样式的内部迭代.但是,这不允许在锁步中迭代两个迭代器:

Using opApply-style internal iteration. This doesn't allow iterating over two iterators in lockstep, though:

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版本一样:

Use ranges. These are slightly harder to write in some cases, but are very efficient and allow lockstep iteration. This can also be iterated over with a foreach loop, exactly like the opApply version:

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

如果您确实需要协同程序风格的东西,则可以使用core.thread.Fiber将范围和opApply组合在一起,但是您可能会发现范围或opApply几乎始终可以满足您的需求.

If you really need coroutine-style stuff you can combine ranges and opApply together using core.thread.Fiber, but you'll probably find that either ranges or opApply does what you need almost all the time.

这篇关于什么是“收益率回报"?等价于D编程语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 13:53