What are some useful or interesting infinite generators? [closed]

陌路散爱 提交于 2020-01-17 06:54:12

问题


What are some clever uses for infinite generators? I've seen lots of seemingly trivial examples like "list all even numbers", but I assume there must be others that have more applicability to real-world scenarios. Concrete examples (in any language that support generators) appreciated!

I'll give a trivial sample as an answer.


回答1:


Look at the Haskell code on http://rosettacode.org/wiki/Hamming_numbers#Haskell; that uses lazy lists (which are somewhat like generators) in a creative way to list all Hamming numbers.




回答2:


A random generator might be considered clever use.




回答3:


Trivial example: yield Fibonacci numbers one at a time (sans overflow checking, in C#):

public static IEnumerable<double> Fibonacci()
{
    double n_minus2 = 1;
    double n_minus1 = 1;
    yield return n_minus2;
    yield return n_minus1;

    while(true)
    {
        double n = n_minus2 + n_minus1;
        yield return n;
        n_minus2 = n_minus1;
        n_minus1 = n;
    }
}


来源:https://stackoverflow.com/questions/4949791/what-are-some-useful-or-interesting-infinite-generators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!