这是C#中的一个简单生成器.
IEnumerable<int> Foo()
{
int a = 1, b = 1;
while(true)
{
yield return b;
int temp = a + b;
a = b;
b = temp;
}
}
Run Code Online (Sandbox Code Playgroud)
如何在Digital Mars D中编写类似的发生器?
(问题是关于收益率报表)
谢谢!
更新.那很有意思.由于我只是生成一个数学序列,因此使用递归可能是一个不错的选择.
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);
}
Run Code Online (Sandbox Code Playgroud)
dsi*_*cha 20
在D中没有确切的等价物.这里有一些粗略的等价物:
使用opApply样式的内部迭代.但是,这不允许以锁步方式迭代两个迭代器:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
使用范围.在某些情况下,这些写入稍微困难一些,但效率非常高并且允许锁步迭代.这也可以通过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; }
}
Run Code Online (Sandbox Code Playgroud)
如果你真的需要coroutine风格的东西,你可以将范围与opApply结合起来使用core.thread.Fiber
,但你可能会发现无论是范围还是opApply几乎所有时间都能满足您的需求.
Meh*_*dad 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);
}
Run Code Online (Sandbox Code Playgroud)
Col*_*Two 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
;
}
Run Code Online (Sandbox Code Playgroud)