What is a “yield return” equivalent in the D programming language?

前端 未结 3 726
小鲜肉
小鲜肉 2021-02-01 17:11

Here is a simple generator in C#.

    IEnumerable Foo()
    {
        int a = 1, b = 1;
        while(true)
        {
            yield return b;
             


        
3条回答
  •  没有蜡笔的小新
    2021-02-01 17:54

    The std.concurrency module now has a Generator class which makes this even easier (and you don't need a third-party library).

    The class is an input range, so it can be used with for loops and all the standard std.range/std.algorithm functions.

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

提交回复
热议问题