问题
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